Send Emails With PHPMailer Library

5:01:00 AM

May it be an email sent to the customer, a confirmation email sent to your agent, or any requirement as such, systems which are being developed now a days incorporate extensive emailing facilities. Almost all the systems developed lately contain email functions and obviously the demand for this feature will increase drastically day by day.

The challenge we, PHP developers, have got in hand is to find an answer to the question “How do we tackle this requirement effectively?”. One might immediately say “Simple! Why not try out the PHP’s inbuilt email function?”. Well, let’s be honest, that’s a good answer, but not the BEST.The smartest answer is “PHPMailer Library”.

mailer() function; php inbuilt function for sending E-mail, hide a lot of underlying mechanism of it from developer while PHPMailer function gives the developer a vast play ground with all the fancy and cool (+geeky) stuff to play around with.
Let’s see how to deal with PHPMailer library.

First of all, you have to install and load the PHPMailer library. We can do this via Composer. All you have to do is,  open your command prompt, go to your project folder and type

composer require phpmailer/phpmailer:~5.2

This will install PHP Mailer to your system and a folder named “vendor” will be created inside your project folder.

Here's a look at the inside of PHPMailer folder. Most vital files are listed below
    • class.phpmailer.php -Includes all the PHPMailer methods
    • class.pop3.php - Handles the POP functions
    • class.smtp.php - Handles the SMTP functions
    • PHPMailerAutoload.php -Handles the loading of the library. This is a SPL-compatible auto loader and using of this file is the preferred way of loading the library.
Lets start with loading PHPMailer library to our program.
require ('vendor/autoload.php');
That’s it..You are good to go with PHPMailer now. Important thing to note here is autoload class does not throw errors if it can't find classes,it keeps a list of errors, allowing you to use your own method to handle those errors.

STEP ONE -  Create an instance of PHPMailer
$mail = new PHPMailer();
or better
$mail = new PHPMailer(true);
The “true” parameter means it will throw exceptions on errors, which we need to catch.

STEP TWO - Choice of protocol
We can chose either SMTP or POP protocol. In this tutorial we are going to use SMTP.
$mail = IsSMTP();
calling IsSMTP method tells PHPMailer that, this is the protocol we are going to use.
$mail->SMTPDebug = true
This enables the SMTP debug information. you can set this to true or false.
$mail->SMTPAuth   = true;
This enables the SMTP authentication.If you set this to “false” there is no authentication. So you don’t need to set username or password parameters.(We are going to discuss about these parameters later)

STEP Three -Set up SMTP Server and related configuration
$mail->SMTPSecure = "tls";   
you can use either “ssl” or “tls”. This configuration depends on your choice of SMTP server. If you are using gmail as your smtp server this should be set to “tls”. (SSL and TLS both provide a way to encrypt a communication channel between two computers )
$mail->Host = “”
Set the gmail as your SMTP server.
Set the smtp port to access gmail server. Again this port number depends on your SMTP server.(for gmail server it’s 587)
$mail->Username   = “GMAIL username”; 
$mail->Password   = “GMAIL password”;

If you set the authentication to “true[SMTPAuth = true] you have to set both these parameters to connect with Gmail smtp server.

STEP Four - Set up E-mail parameters
$mail->SetFrom(“FROM_EMAIL ADDRESS”, “FROM_NAME”);    
This will set the From address and name                     
If you set this, all the replies from the Email recipient will be sent to this address.
$mail->Subject = 'Subject of the Email';
This will Set the subject line.
$mail->AddAddress(“TO_EMAIL_ADDRESS”, “TO_NAME”);
Email address and name of the Email recipient.
              $mail->AddCC(“CC_EMAIL”, “CC_NAME”);
       $mail->AddBCC(“BCC_EMAIL”, “BCC_NAME”);
These will set the CC and BCC option related with Email sending
$mail->msgHTML(“HTML Message Content”);
This method initiate IsHTML() method to true(which means, this method processes Email body as a HTML content) and evaluates the message and returns modifications for inline images and backgrounds.

As an alternative to above method we can use,
$mail->AltBody = 'This is a plain-text message body';
Which  returns plain text only Email body.
$mail->addAttachment('path_of_the_attachment file',’name of the file’);
(optionally you can add two more parameters to this method,
“encryption type” and “file type”. note that name parameter is optional too)
This is the End. This method creates message body and assigns Mailer. If the Email is not sent successfully then it returns false.

Finally  we’ll look at our completed code.Here I have added PHPMailer exception handling too.

$FROM_NAME= "from_name";

$CC_NAME = “cc_name”;
$Subject=”PHPMailer Email”;
$Message=”<h3>PHPMailer tutorial</h3><p>This tutorial will teach you how to send a email with PHPMAiler library</p><h4>Happy coding </h4>”;
$mail = new PHPMailer(true);

   $mail->SMTPDebug = true;
   $mail->SMTPAuth = true;
   $mail->SMTPSecure = "tls";
   $mail->AddReplyTo($REPLY_EMAIL, $REPLY_NAME);
   $mail->AddAddress($CUSTOMER_EMAIL, $CUSTOMER_NAME);
   $mail->Subject = $Subject;


} catch (phpmailerException $e) {
      echo $e->errorMessage();
} catch (Exception $e) {
      echo $e->getMessage();


Now we have a fully functioning mailer class. All you have to do is create a nice front end file like “Contact Us” or “Write to us” and submit it to above class we created. Fun part is, inside message body you can use any HTML tag you like  and format your Email body in anyway you want.
Of Course PHPMailer is slightly slower than php in built mailer() function.But if you are looking for  nicely formatted emails to be sent to a list of targeted recipients each day PHP Mailer is your best bet.

You can find the source code of this article from GitHub.

You Might Also Like


Popular Posts