Wednesday, August 27, 2014

PHP Send Mail with XAMPP Localhost Using PHPMailer

Hi All,

When developing a website, you might want to send a mail using PHP script through the localhost, specially when developing pages like Contact Us pages.

There are several ways we can do this.

One way is to send the mail using XAMPP by changing the php.ini and sendmail.ini. I have tried to use this method, but couldn't get any good result. In some posts readers have complained that it does work at times, but not every time.

Another way is using PHPMailer. It's an opensource code that helps to send mails via PHP. This is the best method I came across and it's really really easy to integrate in your site. You can read more about PHPMailer from this link.

NOTE : Before you are trying to work with the PHPMailer and Google SMTP, one important thing you should do is to Allow Less Secure Access in the Google Account you are using to Authenticate mailing. You can do it using this link

Download the PHPMailer from github and extract it to your site. If you are using XAMPP the location would be like "C:\xampp\htdocs\your_site\email". Now first you have to develop a php file that can submit a form. Following is a template of a contact form. You can add additional fields as you want.

<div class="col-md-8" id="divMain">

    <h1>Contact Us</h1>
    <h3 style="color:#8EB037;"><?php echo @$_GET['msg'];?></h3>
    <hr/>
 <!--Start Contact form -->                                                  
    <form name="contactform" method="post" action="email/index.php" class="form-horizontal" role="form" onsubmit="return validation();">
        <div class="form-group">
            <label for="inputName" class="col-md-2 control-label" style="text-align:left;">Name</label>
            <div class="col-md-10">
                <input type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name">
            </div>
        </div>
        <div class="form-group">
            <label for="inputEmail1" class="col-md-2 control-label" style="text-align:left;">Email</label>
            <div class="col-md-10">
                <input type="text" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email">
            </div>
        </div>
        <div class="form-group">
            <label for="inputSubject" class="col-md-2 control-label" style="text-align:left;">Subject</label>
            <div class="col-md-10">
                <input type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword1" class="col-md-2 control-label" style="text-align:left;">Message</label>
            <div class="col-md-10">
                <textarea class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..."></textarea>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="submit" class="btn btn-primary pull-right" value="submit" name="submit" >
                    Send Message
                </button>
            </div>
        </div>
    </form>  
 <!--End Contact form -->            
</div>

Note : Here I have used bootstrap 3 for the contact form. I placed my contact form in the directory "C:\xampp\htdocs\your_site\contact.php".

Then in the email folder ("C:\xampp\htdocs\your_site\email") include the javascript validation for the validation of form fields and index.php for sending the mail. Following is the index.php code.

require_once 'phpmailer/PHPMailerAutoload.php';

 if(isset($_POST['submit']))
 {
 $name = $_POST['inputName'];
 $email = $_POST['inputEmail'];
 $query = $_POST['inputMessage'];
 $email_from = $name.'<'.$email.'>';
 $subject = $_POST['inputSubject'];

 $message="   
    
   Name:
  $name     
  

   Email-Id:
  $email     
  

   Message:
  $query     

 ";

 $mail = new PHPMailer;

 $mail->isSMTP(); // Set mailer to use SMTP
 $mail->SMTPAuth = true; // Enable SMTP authentication
 //$mail->SMTPDebug = 2; //Please enable debug if you want to check if the mail sent successfully.

 $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
 $mail->Username = 'yourname@gmail.com';    // SMTP username
 $mail->Password = 'yourpassword';  // SMTP password
 $mail->SMTPSecure = 'ssl';   // Enable encryption, 'ssl' also accepted
 $mail->Port = 465; 

 $mail->addAddress('yourname@gmail.com', 'YourName');
 $mail->From = $email;
 $mail->FromName = $name;
 $mail->Subject = $subject;
 $mail->Body    = $message;
 $mail->AltBody = $message;

 if(!$mail->send()) {
  header("Location:../contact.php?msg=Error To send Email !");
 } else {
  header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
 }
 }

Following is the javascript validation

 function validation()
 {
    
 var contactname=document.contactform.inputName.value;
 var name_exp=/^[A-Za-z\s]+$/;
 if(contactname=='')
 {
  alert("Name Field Should Not Be Empty!");
  document.contactform.inputName.focus();
  return false;
 }
 else if(!contactname.match(name_exp))
 {
  alert("Invalid Name field!");
  document.contactform.inputName.focus();
  return false;
 }
 
 var email=document.contactform.inputEmail.value;
 //var email_exp=/^[A-Za-z0-9\.-_\$]+@[A-Za-z]+\.[a-z]{2,4}$/;
 var email_exp=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
 if(email=='')
 {
  alert("Please Enter Email-Id!");
  document.contactform.inputEmail.focus();
  return false;
 }
 else if(!email.match(email_exp))
 {
  alert("Invalid Email ID !");
  document.contactform.inputEmail.focus();
  return false;
 }
 
 
 var message=document.contactform.inputMessage.value;
 if(message=='')
 {
  alert("Query Field Should Not Be Empty!");
  document.contactform.inputMessage.focus();
  return false;
 }


 var subject = document.contactform.inputSubject.value;
 if(subject=='')
 {
  alert("Subject Should Not Be Empty!")
  document.contactform.inputSubject.focus();
  return false;
 }

    return true;
 }


Place the javascript file in the "C:\xampp\htdocs\your_site\email".

Now you can send the mails using your contact form.

Hope that helps,
Thank You.

Reference : https://github.com/Synchro/PHPMailer

6 comments: