What is PHPMailer
PHPMailer is the classic email sending library for PHP. It supports several ways of sending email messages such as mail(), Sendmail, qmail, and direct dispatch to SMTP servers. In addition, it provides a list of advanced features:
- SMTP authentication
- secure/MIME encryption
- support of TLS and SSL protocols
- HTML content along with plain text
- multiple fs, string, and binary attachments
- embedded images support
Sending Email With PHPMailer and SMTP
To send emails with PHPMailer and SMTP, you need to install PHPMailer and configure SMTP settings first.
How to install PHPMailer
Up to version 5, PHPMailer was providing âPHPMailerAutoload.phpâ file, so all that was needed was to include it in your script and create a PHPMailer instance. Starting from PHPMailer 6.0 release in August 2017, you need to install it, preferably via Composer, a dependency manager for PHP (this way is recommended by PHPMailerâs creators on Github). After installing Composer, add this line to your composer.json file:
"phpmailer/phpmailer": "~6.1"
or run
composer require phpmailer/phpmailer
If you donât want to install Composer, for example, while working within a testing environment, you can add PHPMailer manually. Download files with PHPMailer source code, then copy the contents of the PHPMailer folder to one of the include_path directories specified in your PHP configuration, and load each class file manually:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
Adding Exception class will help you handle errors and debug them. In PHP it works similarly to the other programming languages. So, without it, if there is an error in your email sending code, you will just see a message saying Exception class is not found, but you wonât be provided with any details on how to debug it. We will describe debugging is a separate section of this post.
To see detailed instructions on installation, check PHPMailer documentation on Github.
SMTP configuration
How to send test messages with PHPMailer?
To test PHP mail functionality, we will use Mailtrap, a fake SMTP server, so as not to flood our inboxes or even worse, the inboxes of our customers. Once you make sure that everything works properly and your email messages look right, you will be able to easily substitute the SMTP settings in our examples with your real serverâs.
If you are not using Mailtrap yet, create a free account , go to your Inbox, and copy the following values from the SMTP settings tab to your PHPMailer script:
server host ($mail->Host = âsmtp.mailtrap.ioâ)
username ($mail->Username = â1a2b3c4d5e6f7gâ (example, generated by Mailtrap)
password ($mail->Password = â1a2b3c4d5e6f7gâ (example, generated by Mailtrap)
and port ($mail->Port = 25, or 465, or 2525
There is one more point left to mention about SMTP: POP-before-SMTP for authentication. This method is almost fully replaced by the SMTP authentication but still can be used sometimes. Its main advantage is the transparency for the user who is sending an email. Checkthis Github page to get the example of using POP-before-SMTP with PHPMailer.
Sending HTML email via SMTP with PHPMailer
Most likely, you will use HTML to design your email notification. So, letâs review some examples of using HTML methods and attributes.
Basic HTML message
If you have used Composer for installation, include the Composer generated autoload.php file:
require 'path/to/composer/vendor/autoload.php';
If you have installed PHPMailer manually, initialize it like this:
require path/to/PHPMailer/src/PHPMailer.php';
require path/to/PHPMailer/src/SMTP.php';
require path/to/PHPMailer/src/Exception.php';
Then create the PHPMailer class:
<?php
use PHPMailer\PHPMailer\PHPMailer;
The next step is to create a new PHPMailer object:
$mail = new PHPMailer();
Now letâs move to an SMTP configuration:
$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = '1a2b3c4d5e6f7g'; //paste one generated by Mailtrap
$mail->Password = '1a2b3c4d5e6f7gâ //paste one generated by Mailtrap
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;
Specify PHPMailer headers:
$mail->setFrom('info@mailtrap.io', 'Mailtrap');
$mail->addReplyTo('info@mailtrap.io', 'Mailtrap');
$mail->addAddress('recipient1@mailtrap.io', 'Tim');
$mail->addCC('cc1@example.com', 'Elena');
$mail->addBCC('bcc1@example.com', 'Alex');
If you need to add several addresses, specify each of them as a new command:$mail->AddBCC('bcc2@example.com', 'Anna');
$mail->AddBCC('bcc3@example.com', 'Mark');
With PHPMailer, you can loop your message and send it to multiple recipients. In particular, you can read a list from the table. We will review such examples a bit later in this post, and now letâs get back to our basic message.Â
Set a subject:
$mail->Subject = 'Test Email via Mailtrap SMTP using PHPMailer';
Then set the email format to HTML with isHTML(true) property:
$mail->isHTML(true);
Now you can input the desired content:
$mailContent = "<h1>Send HTML Email using SMTP in PHP</h1>
<p>This is a test email Iâm sending using SMTP mail server with PHPMailer.</p>";
$mail->Body = $mailContent;
With PHPMailer, you can also make a nice HTML email, with custom formatting, images, and send emails with attachments. For your convenience, PHPMailer provides an option to read an HTML message body from an external file, convert referenced images to embedded as well as convert HTML into a basic plain-text alternative body. This way, you will not overload your message sending code with HTML and will be able to update your HTML template independently. To include a separate HTML file, add these attributes:
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
In the end, specify the email sending attributes:
if($mail->send()){
echo 'Message has been sent';
}else{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
The result âMessage has been sentâ informs you that your code executes correctly. To check the delivery result and details, go to your Mailtrap inbox: your messages will get there in seconds.Â
With Mailtrap, you will be able to review your HTML code, raw data, perform email browser testing as well as make sure your message wonât be marked as spam, or your sending domain wonât go blacklisted.
HTML email with attachments
There are two options for adding files to your message:Â
- Enclose a file from your filesystem â like you can make it in the email client. In this case, your files should be saved in the same directory as the script.
- Also, a file can be inlined into your message, this is valid for images.
- Add a string attachment â in this case, the data stored in a variable is attached to the message. It can be extracted from a database, from example, so you donât need to save it as a file, actually.Â
To attach a file, you just need to specify its path. Also, you can add a filename but itâs optional: the script will use the actual name of your file:
$mail->addAttachment('path/to/invoice1.pdf', 'invoice1.pdf');
To add another file, repeat the command:
$mail->addAttachment('path/to/calculation1.xlsx', 'calculation1.xlsx');
To add an attachment from the string, use addStringAttachment() command. You should pass the content and the filename:
$mysql_data = $mysql_row['blob_data'];
$mail->addStringAttachment($mysql_data, 'db_data.db');
This is an example of adding data stored as a BLOB (Binary Large OBject) from MySQL database.
Alternatively, you can use a remote URL, like below:
$mail->addStringAttachment(file_get_contents($url), 'myfile.pdf');
To embed an image, we use CID attachments here:
$mail->addEmbeddedImage('path/to/image_file.jpg', 'image_cid');
$mail->isHTML(true);
$mail->Body = '<img src="cid:image_cid">';
Finally, letâs review an example of a whole message with an inlined image and internal HTML body:
<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'path/to/composer/vendor/autoload.php';
$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = 'paste one generated by Mailtrap';
$mail->Password = 'paste one generated by Mailtrapâ
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;
$mail->setFrom('from@example.com', 'First Last');
$mail->addReplyTo('towho@example.com', 'John Doe';
$mail->isHTML(true);
$mail->Subject = "PHPMailer SMTP test";
$mail->addEmbeddedImage('path/to/image_file.jpg', 'image_cid');
$mail->Body = '<img src="cid:image_cid"> Mail body in HTML';
$mail->AltBody = 'This is the plain text version of the email content';
if(!$mail->send()){
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Message has been sent';
The result âMessage has been sentâ informs you that your code is executing correctly. To check the delivery result and details, go to your Mailtrap inbox: your messages will get there in seconds.