Send Email in PHP using Gmail SMTP

by Vincy. Last modified on May 26th, 2023.

Sending email is a simple and straightforward task in PHP. Yes! trust me. For some beginners and sometimes even the experienced too struggle to send an email using PHP.

Let’s solve it once forever with this article.

Sending an email with PHP’s core function mail() is simpler and the easier option.

<?php
// The message
$message = "Hi, how are you doing?";
mail('phppot@example.com', 'Email Subject', $message);
?>

This PHP’s mail function does not have advanced features for sending an email. For example, we cannot send attachments using PHP’s mail(). To send email via Google’s Gmail SMTP, we need sophisticated options.

So let us take the best and most popular route. There are so many libraries available for PHP for different purposes. If there is one library that is unarguably the best and the most used one, it is PHPMailer.

When you want to send email in a PHP contact form, you may essentially need a SMTP server. If you do not have access to a SMTP server, then you may use Google’s GMail SMTP.

Let us see how to send email in PHP using PHPMailer library via Gmail SMTP. Following is the project structure. See, the PHPMailer library is added as a dependency in the vendor folder.

Email Gmail SMTP project structure

We will use PHPMailer class for sending emails by using Gmail SMTP server. Some of the features of PHPMailer are,

  • Allows both plain text and HTML content as email body.
  • Allows array of email addresses for to|cc|bcc|reply-to.
  • It provides Secure/MIME encryption.
  • It supports various encoding techniques binary, base64 and etc.
  • It has multiple language support (English by default).
  • It provides email validation, SMTP authentication, word wrapping and more.

PHP Script for Sending Email using Gmail SMTP

It is important to have the PHPMailer library in the project. There are two different ways to include it in your project. The best way is to use the composer and add it as a dependency in the JSON file.

If you do not have have knowledge or have never used it, I would strongly recommend you to learn composer. It is the popular dependency manager in PHP and will be quite useful.

Without composer, you can download the PHPMailer, unzip and put it inside the vendor folder in your project. In this example, I have used the same method.

When we send email using Gmail SMTP make sure to set SMTPAuth as TRUE. Use your Gmail Username and Password as given below. This example code is adapted from PHPMailer’s example script.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';

// passing true in constructor enables exceptions in PHPMailer
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; // for detailed debug output
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->Username = 'example@gmail.com'; // YOUR gmail email
    $mail->Password = 'YOUR_GMAIL_PASSWORD'; // YOUR gmail password

    // Sender and recipient settings
    $mail->setFrom('example@gmail.com', 'Sender Name');
    $mail->addAddress('phppot@example.com', 'Receiver Name');
    $mail->addReplyTo('example@gmail.com', 'Sender Name'); // to set the reply to

    // Setting the email content
    $mail->IsHTML(true);
    $mail->Subject = "Send email using Gmail SMTP and PHPMailer";
    $mail->Body = 'HTML message body. <b>Gmail</b> SMTP email body.';
    $mail->AltBody = 'Plain text message body for non-HTML email client. Gmail SMTP email body.';

    $mail->send();
    echo "Email message sent.";
} catch (Exception $e) {
    echo "Error in sending email. Mailer Error: {$mail->ErrorInfo}";
}
?>

For setting FromEmail and FromName, we can either use SetFrom() function or use PHPMailer properties PHPMailer::From and PHPMailer::FromName. For example,

<?php
$mail->From = "from email address";
$mail->FromName = "from name";
?>

AddReplyTo(), AddAddress() functions will accept array of email addresses, and name is optional.

If we have HTML content as mail body, we need to set content body text/HTML by using,

$mail->IsHTML(true);

After setting all properties and mailer information with the PHPMailer object, PHPMailer::send() function returns TRUE on successful mail transfer and FALSE on failure.

Google configuration to send email via Gmail SMTP

I am not sure if it is formally approved by Google to use its SMTP
server to send email in this way. I do not see any information
prohibiting it either.

  1. Disable two-factor authentication (This step is applicable, only if
    you have already enabled it.)
  2. Allow “Less secure app access”: Login to your Gmail account and
    then go to page https://myaccount.google.com/lesssecureapps and Turn
    it On.
  3. On fist usage of the smtp email, Google ‘may’ send a warning
    message to you as below, Someone just used your password to try
    to sign in to your account from a non-Google app. Google blocked
    them, but you should check what happened. Review your account
    activity to make sure that no one else has access....
    Login to your Gmail account and give confirmation that it is you.
    Say yes!

Now you can send email in PHP using Google Gmail SMTP for free. Refer to code a custom Gmail email inbox using PHP with IMAP.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Send Email in PHP using Gmail SMTP”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page