How to Send an Email via Gmail SMTP Server using PHP

Last Updated, 2021-01-04 smtp gmail php

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


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.


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.
  • 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.

  2. Make sure that 2-Step-Verification is disabled.

  3. Turn ON the "Less Secure App" access or click here.

  4. If 2-step-verification is enabled, then you will have to create app password for your application or device.

  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.

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 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 ""
  • 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->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       = "";
$mail->Username   = "";
$mail->Password   = "your-gmail-password";


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

$mail->AddAddress("recipient-email@domain", "recipient-name");
$mail->SetFrom("", "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:

if(!$mail->Send()) {
  echo "Error while sending Email.";
} 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 z2sm11041738pfq.58 - gsmtp
SMTP Error: Could not authenticate.
SMTP connect() failed.
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 f3sm5807314pgj.62 - gsmtp
SMTP Error: Could not authenticate.
SMTP connect() failed.
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: at your service, [] 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://";


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 (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 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:// (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.

Error 8: Emails from PHP code going in Spam

Defintely this is not an error, but definitely a point of concern. One of the most common reason of 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: <credentials hidden>
CLIENT -> SERVER: <credentials hidden>
CLIENT -> SERVER: RCPT TO:<recipient-email@domain>
CLIENT -> SERVER: RCPT TO:<cc-recipient-email@domain>
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 <>
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 (
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--
email sent.



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 ?>

Image Icon

Emails sent from your PHP application landing in Spam?

The most common reason for emails landing in spam is the domain or IP blacklist. Use tools to check the blacklist status and ways to improve your email delivery.

Free Blacklist CheckScans across 100+ DNSBLs