How to Send an Email via Gmail SMTP Server using PHP

Published on 2019-09-25ยท Updated on 2024-01-25

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

In this tutorial, you will learn how to send emails in PHP using the PHPMailer library via Gmail SMTP.  

PHPMailer is a tool in the Email API category of a tech stack. PHPMailer is more popular than simple email since it provides more capabilities such as attachments, encryption, authentication, and so on. It also streamlines the process of sending HTML emails.

Prerequisites

Before starting with steps on how to send mail using SMTP in PHP example, let's first see what few limits with Gmail SMTP servers are and how to overcome some of these:

  • Gmail limits the number of recipients in a single email and the number of emails that can be sent per day. The current limit is 500 Emails in a day or 500 recipients in a single email. You can't increase this limit. If you want to send above these limits, you need to integrate with third-party email delivery platforms like Email API, Sendgrid, etc.
  • On reaching threshold limits, you won't be able to send messages for the next 24 hours. Once this temporary suspension period ends, the counter gets reset automatically, and the user can resume sending emails.
  • By default, third-party apps/codes are not allowed to send emails using your Gmail account. And, hence there are a few settings that need to be done at your end:

How To Enable Email Sending In Gmail?


Before sending emails using Gmail's SMTP Server, you can make some security and permission level settings under your Google Account Security Settings.

  1. Open your Gmail account settings. Click on Sign-in and Security. Post that, navigate to connected apps and sites, and now enable two-factor authentication. 
  2. Create an app password. The app password should be the password you use in your SMTP settings. You can generate an app password by visiting this page while logged into your Google account.
  3. Turn ON the "Less Secure App" access or click here.
  4. For security measures, Google may require you to complete this additional step while signing in.

Note: It may take an hour or more to reflect any security changes

OAuth2: OAuth2 is the most difficult, yet it is still the recommended technique for authorizing PHPMailer to send emails through Gmail. Fortunately, oauth2-google exists. It is a package for the PHP League's OAuth 2.0 Client that supports Google OAuth 2.0. PHP 7.0 - PHP 7.3 are supported. 

To use it, you must first obtain a Google client ID and client secret. To get started, refer to this Google instruction.  

 

Writing the PHP Code to Send Email using Gmail SMTP

Step 1:  Download the PHPMailer library from this GitHub link. (Refer to PHPMailer documentation on GitHub for detailed installation instructions.) To directly download the .zip file, use this link.

Unzip the master.zip in your application directory and run the following command from your application directory.

composer require phpmailer/phpmailer

Composer is the popular dependency manager in PHP and will be quite useful. Composer is the recommended way to install PHPMailer.

Step 2: Writing the PHP Code to make an SMTP connection

  • Using your Gmail credentials, connect to host "smtp.gmail.com"
  • Click here for some more Examples and Tutorials of PHPMailer

Step 3: Include packages and files for PHPMailer and SMTP protocol:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

 

Step 4: Initialize PHP Mailer and set SMTP as the mailing protocol:

$mail = new PHPMailer(); $mail->IsSMTP(); $mail->Mailer = "smtp";

 

Step 5: Set the required parameters for making an SMTP connection, like server, port, and account credentials. SSL and TLS are cryptographic protocols that provide authentication and data encryption between servers, machines, and applications operating over a network. SSL is the predecessor to TLS.

$mail->SMTPDebug  = 1;  
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Host       = "smtp.gmail.com";
$mail->Username   = "[email protected]";
$mail->Password   = "your-gmail-password";

 

Step 6: Set the required parameters for email header and body:

$mail->IsHTML(true);
$mail->AddAddress("recipient-email@domain", "recipient-name");
$mail->SetFrom("[email protected]", "from-name");
$mail->AddReplyTo("reply-to-email@domain", "reply-to-name");
$mail->AddCC("cc-recipient-email@domain", "cc-recipient-name");
$mail->Subject = "Test is Test Email sent via Gmail SMTP Server using PHP Mailer";
$content = "<b>This is a Test Email sent via Gmail SMTP Server using PHP mailer class.</b>";

 

Step 7: Send the email and catch required exceptions:

$mail->MsgHTML($content); 
if(!$mail->Send()) {
  echo "Error while sending Email.";
  var_dump($mail);
} else {
  echo "Email sent successfully";
}

 An output email is sent successfully.

Working PHP Code to Send Email Using SMTP Server

Click here to download the complete working PHP code to send email using the Gmail SMTP server. You just need to change a few values, and it should work.

List of Possible Errors And Exceptions

Error 1: Password Command Failed: 534-5.7.9 Application-Specific Password Required๐Ÿ”—

SMTP ERROR: Password command failed: 534-5.7.9 Application-specific password required. Learn more at 534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor z2sm11041738pfq.58 - gsmtp
SMTP Error: Could not authenticate.
CLIENT -> SERVER: QUIT
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Problem sending email.

This mainly happened when SMTP Mail Server Credentials were correct, but the Application Specific Password still needed to be provided.

Error 2: SMTP ERROR: Password Command Failed: 535-5.7.8 Username And Password Not Accepted๐Ÿ”—

SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8  https://support.google.com/mail/?p=BadCredentials f3sm5807314pgj.62 - gsmtp
SMTP Error: Could not authenticate.
CLIENT -> SERVER: QUIT
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Problem sending email.

If you have encountered this error, then this is mainly because the application-specific password is incorrect.

 

Error 3: Invalid Address: (To): Recipient-Email๐Ÿ”—

Invalid address:  (to): recipient-email
Problem sending email.

If you have encountered this error, then this is mainly because the recipient's email is invalid.

 

Error 4: SMTP: SMTP Server Does No Support Authentication๐Ÿ”—

authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]

If you have encountered this error, then this is mainly because your code does not appear to be using TLS/SSL, which is necessary to deliver mail to Google. Also, you should be using port 587 or 465.

Reconfirm once whether the value of $host is set as follows:

$host = "ssl://smtp.gmail.com";

 

Error 5: Stream_socket_client(): Unable To Connect To Smtp.Gmail.Com๐Ÿ”—

Error on Feb 25, 2018 11:14AM - stream_socket_client(): unable to connect to smtp.gmail.com:587 (Connection timed out) in /home/dibya/public_html/dibyasahoo/app/helpers/phpmailer/smtp.php on line 222

If you have encountered this error, then this is mostly because your server cannot connect to smtp.gmail.com on port 587. This is mostly because your hosting provider has some strict firewall rule blocking your server from connecting to any other external server over SMTP port 587.

 

Error 6: SMTP Server Error: 5.5.1 Authentication Required. Learn More At 530 5.5.1๐Ÿ”—

SMTP server error: 5.5.1 Authentication Required. Learn more at 530 5.5.1 

If you have encountered this error, then it is mostly because you have enabled 2FA on your Gmail account or you need to enable access to Less Secure App. Read the above prerequisites to address this problem.

 

Error 7: Message: Fsockopen(): Unable To Connect To Ssl://Smtp.Gmail.Com๐Ÿ”—

Message: fsockopen(): unable to connect to ssl://smtp.gmail.com:25 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. )

If you have encountered this error, then this is mostly because of SSL issue. You need to enable SSL in the php.ini file of your server configuration. In case you are using a XAMPP server, then please check whether it is enabled or not. You will get that in the PHP info.

Error 8: Emails from PHP code going into Spam

This is not an error but a point of concern. One of the most common reasons for emails landing in spam is blacklisting. You should check whether your domain or IP address is blacklisted.

Debugger step-by-step output after sending email successfully

CLIENT -> SERVER: EHLO NL616
CLIENT -> SERVER: STARTTLS
CLIENT -> SERVER: EHLO NL616
CLIENT -> SERVER: AUTH LOGIN
CLIENT -> SERVER: <credentials hidden>
CLIENT -> SERVER: <credentials hidden>
CLIENT -> SERVER: MAIL FROM:<[email protected]>
CLIENT -> SERVER: RCPT TO:<recipient-email@domain>
CLIENT -> SERVER: RCPT TO:<cc-recipient-email@domain>
CLIENT -> SERVER: DATA
CLIENT -> SERVER: Date: Sun, 22 Sep 2019 05:11:15 +0000
CLIENT -> SERVER: To: recipient-name <recipient-email@domain>
CLIENT -> SERVER: From: PHP SMTP Mailer <[email protected]>
CLIENT -> SERVER: Cc: cc-recipient-name <cc-recipient-email@domain>
CLIENT -> SERVER: Reply-To: reply-to-name <reply-to-email@domain>
CLIENT -> SERVER: Subject: Test email using PHP mailer
CLIENT -> SERVER: Message-ID: <UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4@NL616>
CLIENT -> SERVER: X-Mailer: PHPMailer 6.0.7 (https://github.com/PHPMailer/PHPMailer)
CLIENT -> SERVER: MIME-Version: 1.0
CLIENT -> SERVER: Content-Type: multipart/alternative;
CLIENT -> SERVER:  boundary="b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4"
CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
CLIENT -> SERVER: This is a multi-part message in MIME format.
CLIENT -> SERVER: --b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4
CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
CLIENT -> SERVER: This is a test email using PHP mailer class.
CLIENT -> SERVER: --b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4
CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
CLIENT -> SERVER: <b>This is a test email using PHP mailer class.</b>
CLIENT -> SERVER: --b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4--
CLIENT -> SERVER: QUIT
email sent.

 

What are the alternatives to PHPMailer and Gmail? 


Apart from Gmail, which is widely used, numerous alternative free and low-cost email programmes are available. Some of the most similar to Gmail in terms of functionality are:

  • Microsoft Outlook 
  • Zoho Mail
  • Yahoo! Mail 
  • Apple Mail

Along with the default PHP mail() method and the widely used PHPMailer, there are a few other options for sending email. Choosing the best approach is heavily influenced by the primary purpose of your project. Furthermore, it's critical to grasp the automation capabilities, documentation, security level, and available support for that option before deciding. Let's go over the possible alternatives. 

Symfony Mailer 

Symfony is an open-source PHP framework's internal email-sending system. The system supports email creation and sending, CSS inlining, Twig integration, file attachment capabilities, and multipart message compatibility. Symfony Mailer may be natively integrated with the most popular email-sending providers, which is especially significant in our case. 

Stampie 

A simple, non-framework-dependent API Wrapper that is simple to implement into a PHP application. The API wrapper is utilized by Postmark, SendGrid, MailGun, Mandrill, and other third-party email-sending services that you can incorporate into your project.

Conclusion

Hope the steps explained above were helpful and that you can successfully send mail from your Gmail SMTP server using PHP. Feel free to contribute if you encounter an issue not listed as a part of this tutorial. Use the comments section to ask/share any feedback.

<? Happy Coding ?>

Excited about the latest in Bulk Email Marketing! Check out this insightful blog on Gmail and Yahoo updates in the email marketing landscape.

Explore the Blog - Here

Stay ahead of the game with valuable insights on optimizing your email campaigns! ๐Ÿ“ฌ

Grade My Email
Check your spam now?

Netcorecloud's toolkit is the solution to all your email problems.

Gaurang Acharya

You can also explore

Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.

Deploy emails that are
screenshot worthy!

Stop settling for static emails - use Netcore's platform to create dynamic, interactive emails that convert.
Let's Deploy
Get Started Now