BLOGS

Send an Email via Gmail SMTP Server using PHP

In this Blog, 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.
  • 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 Setting.
  2. Make sure that 2-Step-Verification is disabled.
  3. Turn ON the “Less Secure App” access.
  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.

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

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”
Step 3: Include packages and files for PHPMailer and SMTP protocol:

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

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. 

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

Step 7: Send the email and catch required exceptions:

Hope the steps explained above were useful and you were able to successfully send mail from your Gmail SMTP server using PHP.