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.
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.
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:
Before sending emails using Gmail's SMTP Server, you can make some security and permission level settings under your Google Account Security Settings.
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.
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
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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:
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.
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! ๐ฌ
Netcorecloud's toolkit is the solution to all your email problems.
Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.
Gaurang Acharya