PHPMailer is one of the most popular PHP code libraries used by CMS giants such as Drupal, WordPress, and Joomla, to send emails using Gmail as the email client. With that in mind, it naturally made sense for us to make this tutorial on how to send emails with PHPMailer via Gmail SMTP.
Additionally, we’ll examine the limitations the two have and what alternatives are out there. Similarly, if you’d like to learn more about sending emails with PHP, check out our comprehensive guide on the subject.
How to send emails using PHPMailer and Gmail SMTP?
If you’re new to PHPMailer and want to explore beyond PHPMailer setup for Gmail feel free to read our PHPMailer Guide.
The first step in sending an HTML or a plain text email with PHPMailer is to require PHPMailer to use Composer (one of the most common ways of adding packages to PHP projects).
Add this line to your composer.json file in the “require” {} section:
"phpmailer/phpmailer": "^6.6"
Or open the command prompt in your project root directory and run:
composer require phpmailer/phpmailer
If the package is successfully added you should see the PHPMailer included in the composer.json file
Refer to PHPMailer documentation on Github for detailed installation instructions.
Prior to May 30, 2022, from your Google account security settings “Less secure app access” had to be turned on to send emails using PHPMailer. Since the “Less secure apps” feature that allows third-party software and devices to sign in to your Gmail account is no longer supported by Google you can choose the other more secure options available.
2-Step Verification
The “Less secure app access” is not available for accounts with or without 2-Factor authentication enabled any longer. If 2-step verification is enabled for your Gmail account and you wish to use it with PHPMailer as well, you will need to create an App password to continue by following these Google instructions. It is a 16-digit passcode, which you should put as a value to $mail->Password
.
XOAuth2
OAuth2 is the most complicated but still the recommended method for authenticating PHPMailer to send mail using Gmail. Fortunately, there is oauth2-google. It is a package to support Google OAuth 2.0 for the PHP League’s OAuth 2.0 Client. It supports PHP 7.0 – PHP 7.3.
To use it, you need to get a Google client ID and client secret first. Follow this Google guide to set everything up.
Once completed, install the package with the composer
command and add the authorization details as shown below:
composer require league/oauth2-google
use League\OAuth2\Client\Provider\Google;
$provider = new Google([
'clientId' => '{google-client-id}',
'clientSecret' => '{google-client-secret}',
'redirectUri' => 'https://example.com/callback-url',
]);
For more details, follow the oauth2-google on GitHub.
The next step is to include the PHPMailer library in your PHP file used to write the code for html emails, e.g sendemail.php
`<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once 'vendor/autoload.php';
$mail = new PHPMailer(true);
?>`
After this, you’ll need to enable SMTP authentication by connecting to the SMTP host “smtp.gmail.com“, listing your Gmail credentials and the relevant cryptographic protocol. Note in our example, we use the SSL instead of TLS as the security protocol with port 465.
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com'; //gmail SMTP server
$mail->SMTPAuth = true;
//to view proper logging details for success and error messages
// $mail->SMTPDebug = 1;
$mail->Host = 'smtp.gmail.com'; //gmail SMTP server
$mail->Username = 'email@gmail.com'; //email
$mail->Password = ‘djsdjjhsdjhsdhj’ ; //16 character obtained from app password created
$mail->Port = 465; //SMTP port
$mail->SMTPSecure = "ssl";
Now that all of the configurations are set up, run the following script after entering real values in the placeholders:
//sender information
$mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');
//receiver email address and name
$mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');
// Add cc or bcc
// $mail->addCC('email@mail.com');
// $mail->addBCC('user@mail.com');
$mail->isHTML(true);
$mail->Subject = 'PHPMailer SMTP test';
$mail->Body = "<h4> PHPMailer the awesome Package </h4>
<b>PHPMailer is working fine for sending mail</b>
<p> This is a tutorial to guide you on PHPMailer integration</p>";
// Send mail
if (!$mail->send()) {
echo 'Email not sent an error was encountered: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
$mail->smtpClose();
Here’s an output of the mail sent:
PHPMailer script to send email via Gmail with an attachment
Using the regular mail function in PHP, it’s possible to send emails with attachments. However, this method requires a localhost mail server, writing lengthy code, and increases the chances of bugs in your app that will require lots of troubleshooting in the future. For those reasons, using the PHPMailer script is a more efficient and secure way to go about this.
In the example below, we’ll examine how with PHPMailer you can send both single and multiple attachments. The first step is to pass a directory path of the attachment to the addAttachment
method.
$mail->addAttachment(__DIR__ . '/exampleattachment1.png');
$mail->addAttachment(__DIR__ . '/exampleattachment2.jpg');
Here is what the full code would look like:
<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPAuth = true;
//to view proper logging details for success and error messages
// $mail->SMTPDebug = 1;
$mail->Host = 'smtp.gmail.com'; //gmail SMTP server
$mail->Username = 'email@gmail.com'; //email
$mail->Password = 'ejhdhsdsdh'; //16 character obtained from app password created
$mail->Port = 465; //SMTP port
$mail->SMTPSecure = "ssl";
//sender information
$mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');
//receiver address and name
$mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');
// Add cc or bcc
// $mail->addCC('email@mail.com');
// $mail->addBCC('user@mail.com');
$mail->addAttachment(__DIR__ . '/download.png');
// $mail->addAttachment(__DIR__ . '/exampleattachment2.jpg');
$mail->isHTML(true);
$mail->Subject = 'PHPMailer SMTP test';
$mail->Body = "<h4> PHPMailer the awesome Package </h4>
<b>PHPMailer is working fine for sending mail</b>
<p> This is a tutorial to guide you on PHPMailer integration</p>";
// Send mail
if (!$mail->send()) {
echo 'Email not sent an error was encountered: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
$mail->smtpClose();
Here’s an output of the mail delivery with an attachment:
Additionally, PHPMailer can be used in a PHP contact form to send emails with attachments.
Limitations and possible issues
Prior to developing an app that will have an email-sending functionality with PHPMailer via Gmail, it’s important to understand the limitations of both systems to avoid any SMTP errors.
PHPMailer is a great library that reduces web development time and helps you build email sending and other types of notifications functionality but it’s not without its issues.
In the past security vulnerabilities have been found in the library, in particular those that exposed the mail server to malicious attacks via contact forms on a website.
It is important to note that PHPMailer had the vulnerability patched in since it was exposed and released documentation on how to deal with it.
For most projects that are at a starting point, a regular Gmail account is enough. However, Gmail does have its own limitations and at a certain stage, you might need to switch to a service that fits your needs.
- 500 Emails a day (1 recipient is counted as one email)
- 24-hour wait time to resume sending after reaching the threshold
What alternatives are there to PHPMailer and Gmail?
Besides Gmail, the dominant choice for many, there are many other free and affordable email clients on the market. Some of the most comparable to Gmail and its functionality includes:
- Zoho Mail
- Microsoft Outlook
- Apple Mail
- Yahoo! Mail
Other than the default PHP mail() function and the widely popular PHPMailer there are a few more alternatives that let you send mail. Choosing the right method highly depends on the main goal of your project. Additionally, prior to making your pick, it’s important to understand the automation capabilities, documentation, security level, and available support for that alternative. Let’s quickly go through the available options.
- Symfony Mailer
An internal email-sending system of the open-source PHP framework, Symfony. The system allows creating and sending emails and comes with CSS inlining, Twig integration, file attachment capabilities, and support for multipart messages. Predominantly important in our context, Symfony Mailer can be directly integrated with the most popular email-sending providers.
- Stampie
A non-framework-dependent straightforward API Wrapper that is easy to integrate into a PHP application. The API wrapper is used in Postmark, SendGrid, MailGun, Mandrill, and many other third-party email-sending services that can be used in your project.
An Email API that allows you to perform quick troubleshooting, and debugging, and prevent sending issues thanks to actionable analytics features. With our Email API/SMTP Relay you can access email logs up to 60 days old, so you can gain greater insight into where your email infrastructure is at.
Mailtrap API integration in your PHP project can be done in a few simple and quick steps:
- Once your domain is set up and verified, from the Sending Domains section go to the API and SMTP tab.
- Choose API in the Integrations window, and PHP from the drop-down menu.
- Copy the API code that will be generated with your credentials and run it.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{"from":{"email":"mailtrap@railsware.com","name":"Mailtrap Test"},"to":[{"email":"example@railsware.com"}],"subject":"You are awesome!","text":"Congrats for sending test email with Mailtrap!","category":"Integration Test"}',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer 7a9d52bc7c1a321c0a5fe786ae0bfc6e',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Testing emails before sending: Why and How?
Adding email-sending functionality in your app is only one part, testing that functionality is a second part that is equally, if not more, important.
Whether it’s finding broken links, checking that the content gets rendered correctly, running spam tests, and checking your deliverability rate are just a few reasons why email testing in PHP apps, or any other for that matter, is critical.
No matter whether it’s a PHP, Python, Javascript, or any other language email library, it’s designed for sending and lacks proper testing capabilities. To do all of these tests, you’ll need a comprehensive tool, one like Mailtrap Email Sandbox. The Sandbox is widely used by developers to inspect emails and perform SMTP debugging in a safe environment without the risk of spamming recipients.
The time-saving solution allows you to capture SMTP traffic from staging, run a spam score, see that the dynamic content is rendered accurately across all types of devices, analyze email headers and validate HTML/CSS.
Thanks for reading our post! It was originally published on Mailtrap Blog by Denys Kontorskyy: https://mailtrap.io/blog/phpmailer-gmail/
Top comments (0)