How to Send an Email via Gmail SMTP Server using PHP

 In All Tutorials
Last Updated On November 20, 2019

In this tutorial, you will learn how to send email in PHP using PHPMailer library via Gmail SMTP.  Like PHPMailer, there are few more good email sending libraries in PHP e.g. PEAR::Mail interface, Swiftmailer etc which can help you easily send mail in php using gmail smtp.

Prerequisites

Before starting with steps on how to send mail using smtp in php example, lets first see what are few limits with Gmail SMTP servers 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 really increase this limit. If you want to send above these limit, then you need to integrate with third-party email delivery platform like Pepipost Sendgrid etc.
  • On reaching threshold limits, you won't be able to send messages for the next 24 hours. Once this temporary suspension period is over, the counter gets reset automatically, and the user can resume sending emails.
  • For more information about email sending limits refer the following links:
  • By default, any third-party apps/codes are not allowed to send emails using your Gmail account. And, hence there are few settings which need to be done at your end:

    How to enable email sending in Gmail?

  1. Before sending emails using the Gmail's SMTP Server, you to make some of the security and permission level settings under your Google Account Security Settings.
    Google Account Security Settings
  2. Make sure that 2-Step-Verification is disabled.
    2-Step Virification Disabled
  3. Turn ON the "Less Secure App" access or click here.
    Less Secure App Access
  4. If 2-step-verification is enabled, then you will have to create app password for your application or device.
    2-Step Virification Enabled
  5. For security measures, Google may require you to complete this additional step while signing-in. Click here to allow access to your Google account using the new device/app.
    New Device-App

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

 

Writing the PHP Code to Send Email using Gmail SMTP

Step 1:  Download PHPMailer library from this github link. To directly download the .zip file, use this link.

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

composer require phpmailer/phpmailer

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"
    • Use port 465, if want SSL
    • Use port 587, if want TLS
  • 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 mailing protocol:

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

 

Step 5: Set required parameters for making an SMTP connection like server, port and account credentials. SSL and TLS are both 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   = "your-email@gmail.com";
$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("from-email@gmail.com", "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";
}

 

Working PHP Code to Send Email Using SMTP Server

Click here to download the complete working PHP code to send email using Gmail SMTP server. You need to just 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 happens mostly when SMTP Mail Server Credentials were correct but Application Specific Password was not 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 mostly 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 mostly because the recipient 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 mostly 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 which is blocking your server to connect 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 this is mostly because you have enabled 2FA on your Gmail account or you have not enabled 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 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 PHP info.

 

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:<from-email@gmail.com>
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 <from-email@gmail.com>
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.

 

Conclusion

Hope the steps explained above were useful and you were able to successfully send mail from your Gmail SMTP server using PHP. Feel free to contribute, in case you encountered some issue which is not listed as a part of this tutorial. Use below comments section to ask/share any feedback.

<? Happy Coding ?>

Recent Posts

Leave a Comment

We are always looking for fresh talent to contribute to our blog. If you have a knack for writing and a passion for email marketing, we would love to have your post on our Guest Blog .

Submit a Guest Post
Pepi thinking

Start typing and press Enter to search

Thank you for your details!

Fill out your information below, and we will send you a PepiAlert, that will describe your domain’s email deliverability situation. Please note that your email address must match the domain, or the domain must be owned by the company matching the email address. We have the right to refuse the request, if we can’t verify the information.

*All fields are required



Pin It on Pinterest