How To Send Email Using PHPMailer in PHP
Introduction
In order to add email services to your PHP application, the PHPMailer class is the ideal choice. PHP frameworks of all kinds are supported (Laravel or Symfony are based on the SwiftMailer library, though, but it is still possible to use PHPMailer as well.) An HTML email with attachments is created using this sophisticated tool, which can then be sent out through SMTP or web server on your local network to a large number of recipients in real time. At the end of this article You'll be able to send a mail using the php library.
Prerequisites
The following criteria must be met in order to follow along with this guide:
- A PHP development environment that runs at least PHP 7.0.
- (Optional) Composer.
Installation
You can send emails using mail(), Sendmail or Qmail, or you can send them directly through SMTP servers. Additional advanced features include:
- SSL/SMTP Authentication
- Attachments in fs, string, and binary
- A plain-text email can be sent to clients that do not support HTML email.
- An active development community maintains it secure and current.
Installing PHPMailer
You must install PHPMailer through Composer, a dependency management for PHP, starting with version 6.0 released in August 2017. This method is suggested by PHPMailer's developers on Github. In your terminal, type the following code to install the library:
composer require phpmailer/phpmailer
PHPMailer can be added manually if you don't want to install Composer in a testing environment, for example. PHPMailer source code files may be downloaded here. Once downloaded, transfer the PHPMailer folder to one of the include path directories provided in your PHP setup, then manually load each class file:
<?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';
See the PHPMailer documentation on Github for comprehensive information on how to install the package without composer.
Use PHPMailer to send emails from a local server
The most likely scenario is that you will utilize HTML to create your email message As a result, you'll be using HTML techniques and attributes to deliver the messages to recipients.
Include the autoload.php
file created by Composer if you have used Composer to install:
require 'path/to/composer/vendor/autoload.php';
This is how to use PHPMailer if you have manually installed it:
require 'path_to_PHPMailer/src/PHPMailer.php';
require 'path_to_PHPMailer/src/SMTP.php';
require 'path_to_PHPMailer/src/Exception.php';
Then include the PHPMailer class:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
Creating a new PHPMailer object is the next stage in the process:
$mail = new PHPMailer();
In the next step, we'll provide the headers:
$mail->setFrom('noreply@example.com', 'Admin');//Add a sender
$mail->addAddress('joe@example.net', 'User');//Add a recipient
$mail->addReplyTo('info@example.com', 'Information');//Add an address that the mail reply should be sent
$mail->addCC('cc@example.com'); //Add a more recipient
$mail->addBCC('bcc@example.com');//Add a more recipient
If you need to add many addresses, create a new code for each one:
$mail->AddBCC('bcc2@example.com', 'mick');
$mail->AddBCC('bcc3@example.com', 'doe');
A file can be attached by specifying its path. Also, you can specify a filename, although it's not required: the script will use the real filename:
$mail->addAttachment('path_to/file.csv', 'file.csv');
In other to add image,you use CID attachments to embed an image here:
$mail->addEmbeddedImage('path_to/image_file.jpg', 'image');
and in the message body add
$mail->Body = '<img src="cid:image">';
Add a subject, indicate that it should delivered with sendmail, and specify that the message contains HTML.
$mail->Subject = 'Test Email Using PHPMailer';
$mail->IsSendmail();sets to send mail using Sendmail.
$mail->isHTML(true); //Set email format to HTML
You may now enter the email body:
$mail->Body = "<H1>Mail body in HTML</H1><p>Email testing</p>";
$mail->AltBody = "This is the plain text version of the email content";
Lastly, define the email sending features as follows:
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
Finally, let's put all the code you've created to send an email together.
<?php
require 'path/to/composer/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer();
$mail->setFrom('noreply@example.com', 'Admin');//Add a sender
$mail->addAddress('joe@example.net', 'User');//Add a recipient
$mail->addReplyTo('info@example.com', 'Information');//Add an address that the mail reply should be sent
$mail->addCC('cc@example.com'); //Add a more recipient
$mail->addBCC('bcc@example.com');//Add a more recipient
$mail->addAttachment('path_to/file.csv', 'file.csv');
$mail->addEmbeddedImage('path_to/image_file.jpg', 'image');
$mail->Subject = 'Test Email Using PHPMailer';
$mail->IsSendmail();sets to send mail using Sendmail.
isHTML(true) sets the email's format to HTML.
$mail->isHTML(true); //Set email format to HTML
$mail->Body = "<H1>Mail body in HTML</H1><p>Email testing<img src="cid:image"></p>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
Sending emails with SMTP server
//Server settings
$mail->SMTPDebug = 1;//Enable SMTP debugging
//Send using SMTP
$mail->isSMTP();
//Enable SMTP authentication
$mail->SMTPAuth = true;
//SMTP Host
$mail->Host='smtp.example.com';
//SMTP username
$mail->Username= 'user@example.com';
//SMTP password
$mail->Password= 'secret';
//Enable implicit TLS encryption
$mail->SMTPSecure= PHPMailer::ENCRYPTION_SMTPS;
//TCP port to connect
$mail->Port= 465;
$mail->isHTML(true); //Set email format to HTML
$mail->Body = "<H1>Mail body in HTML</H1><p>Email testing</p>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
Let's go through the variables now
$mail->SMTPDebug
is used to enable debugging and display error messages.$mail->isSMTP()
is used to notify the PHPMailer to use SMTP to convey messages.$mail->SMTPAuth
is used to set authentication.$mail->Host
is used to define server host$mail->Username
is used to define the username for smtp server host account.$mail->Password
is used to define the password for smtp server host account$mail->SMTPSecure
sets the encryption type.$mail->Port
is used to define server port in which the email should be sent.
Conclusion
As a PHP developer, there's little chance you'll be able to avoid sending emails through script. Using third-party services like mailtrap or mailchimp may be a possibility in some cases, but developing your own email sending library may not be feasible. Therein lies the value of PHPMailer and its equivalents (such as Zend Mail and Swift Mailer). Here we've covered the most frequent uses of Phpmailer: delivering pictures and attachments in HTML emails over SMTP or localhost, as well as debugging settings.