Gmail SMTP with PHP using PHPMailer package.

Yet another PHP problem to solve.
One of my friend asked me to help him out with PHP contact form with Gmail SMTP configuration to send out the leads generated on the website.

1. Change settings in your Gmail to work with SMTP

  1. Login to your gmail account
  2. Go to Manage your google account
  3. Go to Security
  4. Look for less secure app and Turn on the less secure app access

 Visit Google Account Less Secure Apps

2. Setting up PHPMailer

While I was looking for this solution, I came across PHPMailer ( The classic email sending library ).
One of the most important and recommended way to install PHPMailer is composer.

To setup composer, please follow the steps at Download Composer.
To setup PHPMailer use the below command and detail documentation can be found at PHPMailer Github Link.

Create a folder smtp_php_test.

mkdir smtp_php_test
cd smtp_php_test
Run the below command on your terminal/command prompt.
This command will create vendor folder in your smtp_php_test folder with phpmailer package.
composer require phpmailer/phpmailer

After doing so many RnD I came to this final code snippet which works will.

Create a file smtp_test.php. You can use your favorite text editor to create this file.

nano smtp_test.php

Add below snippet to smtp_test.php file.

<?php session_start();
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Generated by composer
//Load Composer's autoloader
require 'vendor/autoload.php';

    //change with your emailID [ FROM ] and name
    $mail_to = '[your-sender-email-address]';
    $mail_to_name = '[your-sender-username]';

    //php mailer
    $mail = new PHPMailer(true);

    //smtp settings and credentials
    $mail->SMTPDebug = 2;

    $mail->Host = '';
    $mail->SMTPAuth = true;
    $mail->Username = $mail_to;
    $mail->Password = '[replace-with-your-superduper-password]';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    //recipients - from
    $mail->setFrom($mail_to, $mail_to_name);

    //recipients - to - send self email.
    $mail->Subject = $subject;

    //send email
    echo 'Message has been sent';
} catch (Exception $e){
    echo 'Message could not be sent. Error: ', $mail->ErrorInfo;

Run and test your PHP code.


Post a Comment