php mail send development

PHP script to send emails using gmail smtp

We can send emails through php mail() function from server but it is not guaranteed that emails will be delivered into inbox because that emails are not authenticated.

Authenticated emails are that emails which sent through a authenticated sender. Here, we will create a scrript to send authenticated emails. 

We will use gmail authentication details to send emails through SMTP. 

Step1: Install PHPMailer Library

In the first step, we will install and download PHPMailer library through the composer command. So open your terminal and run the following command.composer require phpmailer/phpmailer

Above composer command will download all the files of phpmailer with autoloader which will load all the classes.

Step 2: Write script to send email

Now, after downloading phpmailer library we will write a php script to send emails through gmail authentication using phpmailer library.

So, first thing to send emails from gmail smtp we will need to have a gmail account. If you do not have, please go to and signup with a email id and password and these details will be need ed in sendmail.php which we are going to create.

Let’s create a file sendmail.php in the directory where phpmailer library has downloaded and put some code which will work for sending emails. Now sendmail.php file will look a like below.


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once "vendor/autoload.php";
require_once "constants.php";
$mail = new PHPMailer(true);
try {
    $mail->Host = '';  //gmail SMTP server
    $mail->SMTPAuth = true;
    $mail->Username = GMAIL_USERNAME;   //username
    $mail->Password = GMAIL_PASSWORD;   //password
    // Sending mail through smtp secure(ssl/tls)
    $mail->SMTPSecure = 'ssl';  // Can also use 'tls' instead of 'ssl'
    $mail->Port = 465;   // SMTP port Should be 587 whien using 'tls'                  
    $mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');
    // Add attachment
    $mail->addAttachment(__DIR__ . '/sample_file.txt');
    $mail->addAttachment(__DIR__ . '/sample_image.png');
    // isHTML true for sending html body content
    $mail->Subject = 'Email Subject';
    $mail->Body    = '<b>Email Body</b>';
    echo 'Email has been sent';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: '. $mail->ErrorInfo;

Now, the script to send emails is ready to be used. It will use the gmail login details for gmail authentication. After putting correct authentication details, email may not work becuase of the gmail security reason.

You will need ‘Allow less secure app’ to set on like the screeenshot below-

After allowing less secure app your email will work like a charm.