Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How To Send Emails In PHP Using PHPMailer Library

March 29, 2016

4 Min Read
Reading Time: 4 minutes

Although there are many PHP libraries, PHPMailer is one of the most popular one. Although it was released in early 2000s, it is now a very commonly adopted approach among developers for sending emails in PHP. The below shown PHPmailer example highlights the alternative approach of sending emails other than through the mail() function.

Generally speaking, PHPMailer is an alternative to mail() function which is used more often. There come many scenarios when mail() function is not much flexible.

send emails using phpmailer library

You might also like: How To Host PHP On DigitalOcean

7 Advantages of Using PHPMailer Rather Than Mail() Function

There are many advantages of choosing PHPMailer over the mail() function for the purpose of sending email.

  1. Object Oriented

Mail() function is not object oriented whereas PHPMailer possesses an interface which is object oriented.

  1. Headers and Dirty Code Avoidance

In PHPmailer you don’t have to write dirty code. There is no need to create headers in the same way as in mail() function.  PHPMailer actually makes life of a developer painless.

  1. Local Mail Server Limitation

Mail()  function usually needs local mail server for sending out emails whereas PHPMailer uses SMTP. Also, you should have authentication credentials.

  1. Error Sending in Multiple Languages

This library enables you to send error messages in more than 40 languages when message sending fails.

  1. SSL Authentication

This library also supports SMTP protocol and provides authentication over SSL and TLS.

You might also like: How To Add SSL Certificates To Custom PHP Sites

  1. Plain Text Version of Email

It supports sending plaintext email for non-HTML email clients.

  1. Community Support

It has very active community of developers which keeps it up to date.

Applications

Popular content management systems are using the PHPMailer library such as Joomla, Drupal and WordPress.

Installation of Library PHPMailer:

To install PHPmailer in PHP projects, run the below shown composer command::

composer require phpmailer/phpmailer

Email Sending Using PHPMailer on Local Web Server

You can send email from local web server by using the code as below:

<?php require_once "vendor/autoload.php"; //PHPMailer Object 
$mail = new PHPMailer; //From email address and name 
$mail->From = "from@yourdomain.com"; 
$mail->FromName = "Full Name"; //To address and name 
$mail->addAddress("recepient1@example.com", "Recepient Name");//Recipient name is optional
$mail->addAddress("recepient1@example.com"); //Address to which recipient will reply 
$mail->addReplyTo("reply@yourdomain.com", "Reply"); //CC and BCC 
$mail->addCC("cc@example.com"); 
$mail->addBCC("bcc@example.com"); //Send HTML or Plain Text email 
$mail->isHTML(true); 
$mail->Subject = "Subject Text"; 
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content"; 
if(!$mail->send()) 
{
echo "Mailer Error: " . $mail->ErrorInfo; 
} 
else { echo "Message has been sent successfully"; 
}
if(!$mail->send()) 
{ 
echo "Mailer Error: " . $mail->ErrorInfo; 
} 
else 
{ 
echo "Message has been sent successfully"; 
}

Email Sending With Attachments:

You can also send emails with attachments using PHPMailer.

<?php 
require_once "vendor/autoload.php"; 
$mail = new PHPMailer; 
$mail->From = "from@yourdomain.com"; 
$mail->FromName = "Full Name"; 
$mail->addAddress("recipient1@example.com", "Recipient Name"); //Provide file path and name of the attachments 
$mail->addAttachment("file.txt", "File.txt");    
$mail->addAttachment("images/profile.png"); //Filename is optional 
$mail->isHTML(true); 
$mail->Subject = "Subject Text"; 
$mail->Body = "<i>Mail body in HTML</i>"; 
$mail->AltBody = "This is the plain text version of the email content"; 
if(!$mail->send()) 
{ 
echo "Mailer Error: " . $mail->ErrorInfo;
} 
else 
{ 
echo "Message has been sent successfully"; 
}

File.txt and images/profile.png have been attached. They are inside the same directory. Attachments can be added by calling addAttachemnt which is basically an object of PHPMailer. We need to call this object every time as we want to attach more.

By Using SMTP:

You may also send email by SMTP but it requires authentication to send email from another host. It is just in the same way as someone need to make account on hotmail to send email through. SMTP is basically a protocol which send email request to a mail server and sends it to the destination mail server after verification.

Consider the following PHPmailer example to send email using SMTP protocol to a gmail mail server.

<?php

require_once "vendor/autoload.php";

$mail = new PHPMailer;

//Enable SMTP debugging.

$mail->SMTPDebug = 3;                           

//Set PHPMailer to use SMTP.

$mail->isSMTP();        

//Set SMTP host name                      

$mail->Host = "smtp.gmail.com";

//Set this to true if SMTP host requires authentication to send email

$mail->SMTPAuth = true;                      

//Provide username and password

$mail->Username = "name@gmail.com";             

$mail->Password = "super_secret_password";                       

//If SMTP requires TLS encryption then set it

$mail->SMTPSecure = "tls";                       

//Set TCP port to connect to

$mail->Port = 587;                    

$mail->From = "name@gmail.com";

$mail->FromName = "Full Name";

$mail->addAddress("name@example.com", "Recepient Name");

$mail->isHTML(true);

$mail->Subject = "Subject Text";

$mail->Body = "<i>Mail body in HTML</i>";

$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send())

{

echo "Mailer Error: " . $mail->ErrorInfo;

}

else

{

echo "Message has been sent successfully";

}

Before sending email through SMTP, hostname, port number and encryption is required. Also you may need username and password for authentication. It should be noted here that you will be unable to send email to Gmail if two factor authentication is enabled. It will require some additional configuration.

Advantage of Using Remote SMTP:

The biggest advantage of using remote SMTP is that in PHP mail() function, if from is set to other than the local domain name. It will be marked as spam in recipients email server. Consider a scenario. Lets suppose you own abc.com and when you send an email, you mentioned yourself as name@gmail.com and send it to name@yahoo.com. Then, Yahoo server will mark it as spam.

Emails Retrieval Using POP3:

PHPmailer supports POP-before-SMTP verification for sending emails. Hence, it  enables you to send emails using SMTP and authenticate using POP. But you can receive emails from mail servers by POP3.

Error Messages:

$mail ->ErrorInfo is used for returning messages in more than 40 languages. To view error messages in any other language, just copy the language directory from PHPMailer source code to project directory. Consider the following example in which PHPMailer object is set to Russian Language.

$mail->setLanguage("ru");

PHPMailer Is Reliable Email Solution:

This article demonstrates in detail how to use PHPmailer as an alternative approach to send emails in PHP. As a PHP developer, you can’t run away to send emails by programming. Also you may think for third party services for this. There are other alternatives of PHPmailer like Zend mail and swiftmailer.

Cloudways Managed Cloud Platform provides super fast PHP 7 hosting. You can test out the PHPMailer library and how it performs by launching your free trial right now. Get the best of PHP7 through our reliable and proven hosting stack.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Ahmed Khan

Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at ahmed.khan@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!