Please support us by disabling ad blocker for smarttutorials.net ...

Gmail SMTP setup for PHPMailer

Posted by & filed under PHP.

In this tutorial we are going to see how to use Gmail SMTP in PHPMailer to send quoeries of php ajax contact form.

Issues with normal way of sending an email using PHP mail function.

      Most of time when we are sending an email to the receiver will end up in the spam/junk/bulk folders even though we have sent the email in proper way. Maybe it happens because your domain/SMTP server is blacklists with spam, also domain trust factors matters lot.

So when you are sending mail from your domain with normal PHP mail function, most of time will end of in receivers spam/junk/bulk folders.

To avoid this problem, I am using Gmail SMTP server to send the email to receivers (Clients\Subscribers). You may be use other established SMTP server like YAHOO, GMAIL or MailGun etc

Gmail SMTP setup for PHPMailer

Step 1: Create config.php and Keep SMTP Configurations

It is always best practice to keep all your configurations in single place/file. So whenever any of configurations changes happen, then we will go to that particular file and change it. This change will affect all the place we have used the configurations.

So please create config.php file in root folder/directory of your project, and keep all the define the all configs (SMTP, Database credentials etc..)

   
    <?php

    //Gmail SMTP Mail Configuration
    const SMTP = true;
    const SMTP_HOST = "smtp.gmail.com";
    const SMTP_AUTH = true;
    const SMTP_USERNAME = "YOUR.MAIL@gmail.com";
    const SMTP_PASSWORD = "YOUR-GMAIL_PASSWORD";
    const SMTP_SECURE = "tls";
    const SMTP_PORT = 587;
    const TO_EMAIL = "muni@smarttutorials.net";
    const TO_NAME = "muni";
   

Step 2: Create Responsive HTML Contact Form Using Bootstrap 3

I am using Bootstrap 3 to create responsive HTML Contact Form. I have added four input fields to get name, email, subject and message from the user. Here HTML markup of Responsive HTML Contact Form..

   
<div class="email-from">
    <form id="emailForm">
        <div class="form-group">
            <label for="userName">Name</label>
            <input type="text" class="form-control" name="userName" id="userName" placeholder="Your Name">
            <span class="help-block"></span>
        </div>
        <div class="form-group">
            <label for="userEmail">Email address</label>
            <input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Your Email Address">
            <span class="help-block"></span>
        </div>
        <div class="form-group">
            <label for="subject">Subject</label>
            <input type="text" class="form-control" name="subject" id="subject" placeholder="Enter Contact Subject">
            <span class="help-block"></span>
        </div>
        <div class="form-group">
            <label for="message">Your Sweet Message</label>
            <textarea name="message" id="message" rows="6" class="form-control"></textarea>
            <span class="help-block"></span>
        </div>
        <button id="sendMailBtn" data-loading-text="Please Wait..." type="button" class="btn btn-success form-control">Send Request</button>
    </form>
</div>
   

I have done front end validation using jQuery validation plugin. Please refer to following two tutorial to know more about how to validate html form using jQuery validation plugin.

  1. Single Page Sales Promotion Application Using PHP, jQuery, Ajax and PHPMailer

Step 3: Install PHPMailer Via Composer

We are using PHPMailer to send an email using Gmail SMTP. In order to use PHPMailer we need install PHPMailer via Composer or directly download form their GitHub and add it to our project..

Please refer following link to Install PHPMailer Via Composer…

  1. Single Page Sales Promotion Application Using PHP, jQuery, Ajax and PHPMailer Part -2

Step 4: Create ajax.php and Include PHPMailer

Next create ajax.php and Include PHPMailer and config.php file. In order to use both PHPMailer and SMTP configurations we have defined in the config.php file.

   
<?php
require_once 'config.php';
require 'vendor/autoload.php';

$response = [
	'status' => 'success',
	'message' => 'Mail sent successfully',
	'data' => []
];



//Checking is it ajax request
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
  	
    if( !isset($_POST['data']) ) {
        http_response_code(400);
		$response = [
			'status' => 'error',
			'message' => 'Empty post data.',
			'data' => []
		];
		responseHandler($response);
    }
    $data = json_decode($_POST['data'], true); $errors = '';
    
    //Email validation
    if ( isset($data["userEmail"]) && !empty( $data["userEmail"] ) ) {
        $email = trim($data["userEmail"]);
        if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
            $errors .= "$email is <strong>NOT</strong> a valid email address.<br/>";
        }
    } else {
        $errors .= 'Please enter your email address.<br/>';
    }
    //Name Validation
    if ( isset($data["userName"]) && !empty( $data["userName"] ) ) {
        $name = trim( $data["userName"] );
        if ( filter_var($name, FILTER_SANITIZE_STRING) === false){
            $errors .= 'Please enter a valid name.<br/>';
        } elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $errors .= 'Only letters and white space allowed for name...<br/>';
        }
    } else {
        $errors .= 'Please enter your name.<br/>';
    }
    
    //Subject Validation
    if ( isset($data["subject"]) && !empty( $data["subject"] ) ) {
        $subject = trim( $data["subject"] );
        if ( filter_var($subject, FILTER_SANITIZE_STRING) === false){
            $errors .= 'Please enter a subject to send.<br/>';
        }
    } else {
        $errors .= 'Please enter a subject to send.<br/>';
    }
    
    //Message Validation
    if ( isset($data["message"]) && !empty( $data["message"] ) ) {
        $message = trim( $data["message"] );
        if ( filter_var($message, FILTER_SANITIZE_STRING) === false){
            $errors .= 'Please enter a message to send.<br/>';
        }
    } else {
        $errors .= 'Please enter a message to send.<br/>';
    }
    
    
    
    if(!empty( $errors )) {
        http_response_code(400);
		$response = [
			'status' => 'error',
			'message' => $errors,
			'data' => []
		];
		responseHandler($response);
    }
    
    //Filtering out newlines in the email subject
    $subject = str_replace(array("\r","\n"),array(" "," "),$subject);
    $contactContent = file_get_contents('email_templates/contact.html');;
    $parameters = ['name' => $name, 'to_name' => TO_NAME, 'message' => $message ];
    
    if(! send_mail( $email, $subject, $contactContent, $parameters ) ){ 
		//Email sent failed.
		http_response_code(500);
        $response = [
			'status' => 'error',
			'message' => 'Email service failing temporarily Or Maybe you are entered invalid E-mail, Please enter valid email and try again.',
			'data' => []
		];
        responseHandler($response);
    } else {
		//Email successfully sent
        http_response_code(200);
        responseHandler($response);
    }
	
} else {
	//Invalid Ajax request
	http_response_code(403);
	$response = [
		'status' => 'error',
		'message' => 'Invalid request, please try again.',
		'data' => []
	];
	responseHandler($response);
}

/**
 * responseHandler function
 * @param array $response request response
 */
function responseHandler($response)
{
	header('Content-type: application/json');
	echo json_encode($response);
	exit;
}

/**
 * send_mail function
 * @param  string $email             [[Description]]
 * @param  string $Subject           [[Description]]
 * @param  string $message           [[Description]]
 * @param  array [$parameters = []] [[Description]]
 * @return boolean  [[Description]]
 */

function send_mail($email, $Subject, $message, $parameters = []){
	////Parse the message with given parameters
	if( !empty( $parameters ) )$message = parse($message, $parameters);
    
    
    
	$mail = new PHPMailer;
	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = SMTP_HOST;  // Specify main and backup SMTP servers
	$mail->SMTPAuth = SMTP_AUTH;                               // Enable SMTP authentication
	$mail->Username = SMTP_USERNAME;
	$mail->Password = SMTP_PASSWORD;
	$mail->SMTPSecure = SMTP_SECURE;                            // Enable TLS encryption, `ssl` also accepted
	$mail->Port = SMTP_PORT;                                    // TCP port to connect to
	
    if( isset($parameters['name']) )  
        $mail->setFrom($email, $parameters['name']);
    else 
        $mail->setFrom($email);
    
    
	$mail->addAddress(TO_EMAIL);     // Add a recipient
	//$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
    $mail->addBCC(TO_EMAIL);
	
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $Subject;
	
	$mail->Body = $message;
	$mail->AltBody = strip_tags($message);
	
	if(!$mail->send()) {//$mail->ErrorInfo;
        return false;
	} 
	return true;
}


/**
 * parse function
 * @param  string $message    [[Description]]
 * @param  array $parameters [[Description]]
 * @return string [[Description]]
 */
function parse($message, $parameters) {
	foreach ($parameters as $key => $value) {
		$message = str_replace('{'.$key.'}', $value, $message);
	}
	return $message;
}
   

Next I am checking whether the request is valid ajax request or not. If it is not a valid ajax request, then sending response back to the front end with HTTP STATUS CODE of 403.

   
    if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
        //Invalid Ajax request
        http_response_code(403);
        $response = [
            'status' => 'error',
            'message' => 'Invalid request, please try again.',
            'data' => []
        ];
        responseHandler($response);
    }
   

Next sanitizing and validating posted data. If any errors found then I am sending back response with proper status code and error message. if there is errors, then sending response like this .

   
    if(!empty( $errors )) {
        http_response_code(400);
        $response = [
            'status' => 'error',
            'message' => $errors,
            'data' => []
        ];
        responseHandler($response);
    }
   

Next I am calling send_mail() function with necessary parameters in it.

   
    send_mail( $email, $subject, $contactContent, $parameters );
   

Finally within the send_mail() function, I am assigning Gmail SMTP credentials we have defined in the config.php file.

   
    $mail = new PHPMailer;
	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = SMTP_HOST;  // Specify main and backup SMTP servers
	$mail->SMTPAuth = SMTP_AUTH;                               // Enable SMTP authentication
	$mail->Username = SMTP_USERNAME;
	$mail->Password = SMTP_PASSWORD;
	$mail->SMTPSecure = SMTP_SECURE;                            // Enable TLS encryption, `ssl` also accepted
	$mail->Port = SMTP_PORT;   
   

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!