Introduction
In this article, we’ll talk about why and how you should send email with PHPMailer instead of PHP’s mail()
function. One big advantage in using remote SMTP over local mail is that if you use PHP’s mail() function to send email with the from address domain set to anything other than the local domain name (name of the server), then the recipient’s email server’s attack filters will mark it as spam. In order to avoid your message getting caught by spam-filters (although this can not always be guaranteed) we have included all relevant information in following article
We enforce sender verification on our relay server. In short this means the sender should be an existing e-mail address. The long version is that under some circumstances even an existing e-mail address could fail the verification. It is easy to verify if your e-mail address actually exists and it can be done by using a telnet command. Make use of our step by step guide in this article.
PHPMailer advantages:
- It can print various kinds of error messages in more than 40 languages when it fails to send an email.
- It has integrated SMTP protocol support and authentication over SSL and TLS.
- It can send an alternative plain-text version of email for non-HTML email clients.
- It has a very active developer community that keeps it secure and up to date.
PHPMailer is also used by popular PHP content management systems like WordPress, Drupal, and Joomla.
Prerequisites
- Webserver with PHP installed
- existing e-mail address
- SMTP relay
- PHPMailer the latest version which you can download through this link
PHPMailer with Snel SMTP
- Log in to your server with FTP username and password.
- Make sure you’re in your public directory
- Download the latest PHPMailer folder and upload the unzipped contents of the folder
- Create a new PHP file and name it something like phpmail.php
- Add the following code to the file, save it and upload it to the public directory on your server
<?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require './PHPMailer/src/Exception.php'; require './PHPMailer/src/PHPMailer.php'; require './PHPMailer/src/SMTP.php'; $mail = new PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->SMTPDebug = 2; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtprelay.snel.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = false; // Enable SMTP authentication $mail->SMTPSecure = 'tls'; // Enable SSL encryption, TLS also accepted with port 465 $mail->Port = 587; // TCP port to connect to //Recipients $mail->setFrom('[email protected]', 'Mailer'); //This is the email your form sends From $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient address //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Subject line goes here'; $mail->Body = 'Body text goes here'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } ?>
- Send the email by visiting http://”insert-your-domain”/phpmail.php in your webbrowser. It will display the status “Message has been sent” and you now are able send to email with PHPMailer or show errors if there are any.
PHPMailer with local SMTP
Upload the PHPMailer to public directory
Download the latest PHPMailer folder, unzip it and upload the contents of the folder to your server public directory.
Create phpmail.php and add the code from example below
After you have uploaded the content of folder PHPMailer create the phpmail.php file and add the following code to that file, save it and upload it into the public directory.
<?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require './PHPMailer/src/Exception.php'; require './PHPMailer/src/PHPMailer.php'; require './PHPMailer/src/SMTP.php'; $mail = new PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->SMTPDebug = 2; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'localhost'; // Specify main and backup SMTP servers $mail->SMTPAuth = false; // Enable SMTP authentication $mail->SMTPSecure = ''; // Enable SSL encryption, TLS also accepted with port 465 $mail->Port = 25; // TCP port to connect to //Recipients $mail->setFrom('[email protected]', 'Mailer');//This is the email your form sends From $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient address //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Subject line goes here'; $mail->Body = 'Body text goes here'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } ?>
- Test the e-mail
Sending the test mail is straight forward step: Visit in your web-browser http://”insert-your-domain”/phpmail.php and control if the message in the page “Message has been sent” is showing which indicates that our PHPMailer has successfully communicated with a local Postfix setup.
PHPMailer with Gmail
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 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?
- 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.
- Make sure that 2-Step-Verification is disabled.
- Turn ON the “Less Secure App” access or click here.
- If 2-step-verification is enabled, then you will have to create app password for your application or device.
- For security measures, Google may require you to complete this additional step while signing-in. Allow access to your Google account using the new device/app.
Note: It may take an hour or more to reflect any security changes
Now we can start with PHPMailer installation:
Log in to your server
Download PHPMailer from this link to your machine and upload the contents of the folder to your server’s public folder using FTP(S).
Create and edit phpmail.php file
Use text editor to create a new file and give it a name phpmail.php. Use the example code from example and add it into the PHP file we have just created. We would like to point out that we have to change the values as per our domain and usernames.
Important: Gmail requires TLS encryption over SMTP, so we set it accordingly. Before you send via SMTP, you need to find out the host name, port number, encryption type if required and if authentication is required you also need the username and password. Note that having two-factor authentication enabled on Gmail won’t let you use their SMTP with username/password.
<?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require './PHPMailer/src/Exception.php'; require './PHPMailer/src/PHPMailer.php'; require './PHPMailer/src/SMTP.php'; $mail = new PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->SMTPDebug = 2; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = "[email protected]"; $mail->Password = "your-gmail-password"; $mail->SMTPSecure = 'tls'; // Enable SSL encryption, TLS also accepted with port 465 $mail->Port = 587; // TCP port to connect to //Recipients $mail->setFrom('[email protected]', 'Mailer'); //This is the email your form sends From $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient address //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Subject line goes here'; $mail->Body = 'Body text goes here'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } ?>
Save phpmail.php and upload
After you have created and added the code you can upload this file into the public map of your server (not into already present PHPMailer folder but in the public directory).
Send the test email
Visit in your web-browser http://”insert-your-domain”/phpmail.php and it will execute the code and send the test email according to the configuration in your phpmail.php file. In case of any error you will receive a message on the page in the web-browser. You should now be able to send email with PHPMailer
PHPMailer with Microsoft 365
In this example we will show you how to use PHPMailer to send e-mails with Microsoft 365.
To be able to send your emails via your Microsoft 365 email address, you’ll first need to enable SMTP authentication for that email address in your Microsoft 365 admin center. Otherwise, Microsoft 365 will block requests to the SMTP server.
To get started, open the Active users tab in your Microsoft 365 admin center. You can click here to open the right page or expand the hamburger icon in the top-left corner of the admin center and go to Users > Active users.
Then, click on the email account that you want to use to send your WordPress site’s emails. This will expand a slide-out with more options.
In the slide-out, go to the Mail tab. Then, click the Manage email apps option. Next check the option Authenticated SMTP and click on the Save changes button.
Download PhpMailer folder and upload its content to the server
Again make sure you download the PHPMailer package and upload it to public directory on your server.
Create phpmail.php file and add the code
Create phpmail.php file add the following code lines, save it and upload it into the public directory using the FTP client.
<?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require './PHPMailer/src/Exception.php'; require './PHPMailer/src/PHPMailer.php'; require './PHPMailer/src/SMTP.php'; $mail = new PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->SMTPDebug = 2; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.office365.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = "[email protected]"; $mail->Password = "your-mail-password"; $mail->SMTPSecure = 'tls'; // Enable SSL encryption, TLS also accepted with port 465 $mail->Port = 587; // TCP port to connect to //Recipients $mail->setFrom('[email protected]', 'Mailer'); //This is the email your form sends From $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient address //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Subject line goes here'; $mail->Body = 'Body text goes here'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } ?>
Send the test email
In this step visiting in your web-browser http://”insert-your-domain”/phpmail.php will execute the code and send the test email according to the configuration in your phpmail.php file. Presuming that there are no issues here it should show in debug message status “Message has been sent”. You are now able to send email with PHPMailer.
Conclusion
In this tutorial we have reviewed the most common PHPMailer use cases and how to correctly configure the code to work with different SMTP relays. Now you can send email with PHPMailer. If you need more specific examples, consult the “examples” folder inside PHPMailer repository.
Leave a Reply