PHPMailer Gmail Tutorial

PHPMailer is one of the most popular PHP code libraries used by CMS giants such as Drupal, WordPress, and Joomla, to send emails using Gmail as the email client. With that in mind, it naturally made sense for us to make this tutorial on how to send emails with PHPMailer via Gmail SMTP.

Additionally, we’ll examine the limitations the two have and what alternatives are out there. Similarly, if you’d like to learn more about sending emails with PHP, check out our comprehensive guide on the subject.

How to send emails using PHPMailer and Gmail SMTP?

If you’re new to PHPMailer and want to explore beyond PHPMailer setup for Gmail feel free to read our PHPMailer Guide.

The first step in sending an HTML or a plain text email with PHPMailer is to require PHPMailer to use Composer (one of the most common ways of adding packages to PHP projects).

Add this line to your composer.json file in the  “require” {} section:

"phpmailer/phpmailer": "^6.6"

Or open the command prompt in your project root directory and run:

composer require phpmailer/phpmailer

If the package is successfully added you should see the PHPMailer included in the composer.json file

Refer to PHPMailer documentation on Github for detailed installation instructions.

Prior to May 30, 2022, from your Google account security settings “Less secure app access” had to be turned on to send emails using PHPMailer. Since the “Less secure apps” feature that allows third-party software and devices to sign in to your Gmail account is no longer supported by Google you can choose the other more secure options available.

2-Step Verification

The “Less secure app access” is not available for accounts with or without  2-Factor authentication enabled any longer.  If 2-step verification is enabled for your Gmail account and you wish to use it with PHPMailer as well, you will need to create an App password to continue by following these Google instructions. It is a 16-digit passcode, which you should put as a value to $mail->Password.

XOAuth2

OAuth2 is the most complicated but still the recommended method for authenticating PHPMailer to send mail using Gmail. Fortunately, there is oauth2-google. It is a package to support Google OAuth 2.0 for the PHP League’s OAuth 2.0 Client. It supports PHP 7.0 – PHP 7.3.

To use it, you need to get a Google client ID and client secret first. Follow this Google guide to set everything up.

Once completed, install the package with the composercommand and add the authorization details as shown below:

composer require league/oauth2-google

use League\OAuth2\Client\Provider\Google;
$provider = new Google([
'clientId' => '{google-client-id}',
'clientSecret' => '{google-client-secret}',
'redirectUri' => 'https://example.com/callback-url',
]);

For more details, follow the oauth2-google on GitHub.

The next step is to include the PHPMailer library in your PHP file used to write the code for html emails, e.g sendemail.php

<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once 'vendor/autoload.php';

$mail = new PHPMailer(true);
?>

After this, you’ll need to enable SMTP authentication by connecting to the SMTP host “smtp.gmail.com“, listing your Gmail credentials and the relevant cryptographic protocol. Note  in our example, we use the SSL instead of TLS as the security protocol with port 465.

$mail->isSMTP();
$mail->Host = 'smtp.gmail.com'; //gmail SMTP server
$mail->SMTPAuth = true;
//to view proper logging details for success and error messages
// $mail->SMTPDebug = 1;
$mail->Host = 'smtp.gmail.com'; //gmail SMTP server
$mail->Username = 'email@gmail.com'; //email
$mail->Password = ‘djsdjjhsdjhsdhj’ ; //16 character obtained from app password created
$mail->Port = 465; //SMTP port
$mail->SMTPSecure = "ssl";

Now that all of the configurations are set up, run the following script after entering real values in the placeholders:

//sender information
$mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');

//receiver email address and name
$mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');

// Add cc or bcc
// $mail->addCC('email@mail.com');
// $mail->addBCC('user@mail.com');


$mail->isHTML(true);

$mail->Subject = 'PHPMailer SMTP test';
$mail->Body = "<h4> PHPMailer the awesome Package </h4>
<b>PHPMailer is working fine for sending mail</b>
<p> This is a tutorial to guide you on PHPMailer integration</p>";

// Send mail
if (!$mail->send()) {
echo 'Email not sent an error was encountered: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

$mail->smtpClose();

PHPMailer script to send email via Gmail with an attachment

Using the regular mail function in PHP, it’s possible to send emails with attachments. However, this method requires a localhost mail server, writing lengthy code, and increases the chances of bugs in your app that will require lots of troubleshooting in the future. For those reasons, using the PHPMailer script is a more efficient and secure way to go about this.

In the example below, we’ll examine how with PHPMailer you can send both single and multiple attachments. The first step is to pass a directory path of the attachment to the addAttachmentmethod.

$mail->addAttachment(__DIR__ . '/exampleattachment1.png');
$mail->addAttachment(__DIR__ . '/exampleattachment2.jpg');

Here is what the full code would look like:

<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'vendor/autoload.php';

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPAuth = true;
//to view proper logging details for success and error messages
// $mail->SMTPDebug = 1;
$mail->Host = 'smtp.gmail.com'; //gmail SMTP server
$mail->Username = 'email@gmail.com'; //email
$mail->Password = 'ejhdhsdsdh'; //16 character obtained from app password created
$mail->Port = 465; //SMTP port
$mail->SMTPSecure = "ssl";


//sender information
$mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');

//receiver address and name
$mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');


// Add cc or bcc
// $mail->addCC('email@mail.com');
// $mail->addBCC('user@mail.com');

$mail->addAttachment(__DIR__ . '/download.png');
// $mail->addAttachment(__DIR__ . '/exampleattachment2.jpg');


$mail->isHTML(true);

$mail->Subject = 'PHPMailer SMTP test';
$mail->Body = "<h4> PHPMailer the awesome Package </h4>
<b>PHPMailer is working fine for sending mail</b>
<p> This is a tutorial to guide you on PHPMailer integration</p>";

// Send mail
if (!$mail->send()) {
echo 'Email not sent an error was encountered: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

$mail->smtpClose();

Additionally, PHPMailer can be used in a PHP contact form to send emails with attachments.

To learn about limitations and possible issues visit the original blog post. Read more...