How to configure PHPMailer correctly

What is PHPMailer?

PHPMailer is one the most popular mail library. It’s used by many popular CMS platforms like WordPress and Joomla. It is one the most reliable mail library available for PHP.

Your web application development would be incomplete without the email transactions. Whether it’s a sign up or a financial transaction you need to integrate email functionality in your web application.

Mail() function of PHP is an easy way to send emails but it relays on sendmail library of unix systems. Windows don’t include the local mail server so you can’t use the PHP’s mail() function.

In any such cases PHPMailer would be an excellent alternate. It has been a popular project on Google code, Sourceforge and now fully hosted on GitHub. Have a look at the PHPMailer GitHub repository.

Using Gmail

In this article we will be using Gmail for sending email from. You can use any email address for a receiver.

On the December 2014 onwards Google started imposing XOAUTH2 authentication mechanism based on OAuth2. If you follow any PHPMailer tutorial configured for Gmail you probably get the “Please log in via your web browser” error message in response.

To make the test application run you can turn on the less secure app to access your account. We are using it for our testing purpose only.

If you decided to use Gmail email sending for your actual production use, you should follow the PHPMailer Gmail with XOAUTH2 example. It work by creating a web app on Google Developer Console.

The setup:

Let’s implement the PHPMailer to send email using your Gmail account without wasting much of your time.

Here is the link to official PHPMailer library on GitHub. Open the page in a browser tab. We will use the composer to load the library and dependencies.

I am using Netbeans IDE for development purpose. You can use any editor/IDE of your preference.

Create a project directory and add a composer.json file. Add the following dependency line into the composer.json file.

{

“require”: {

“phpmailer/phpmailer”: “~5.2”

}

}

Now run the composer Install command. It will find the specified library and add them to vendor directory inside your project.

Adding library using composer help you get rid of adding each required class manually. You just need to include the autoload file and create the instance of the class(es) you may need. Autoload will take care of adding classes.

If you prefer the minimal installation and don’t want to go for the composer way. You can add the class.phpmailer.php, class.smtp.php, class.pop3.php, and PHPMailerAutoload.php files.

Include the PHPMailerAutoload.php which will handle the loading of other classes.

The code:

Before moving ahead I assume you have created a project, added the PHPMailer library, and turn on the less secure app on your Google account.

Now let’s explore the code. I opted the composer way in my project.

require ‘vendor/autoload.php’;

$mail = new PHPMailer;

As I said I opted for composer way. I included the autoload file and it will handle the other class file inclusion. All I need to care about is creating the instance of class.

$mail is the instance of PHPMailer class. We will use the same object configure various maling properties and access the function of PHPMailer to send an email.

$mail->SMTPDebug = 3;

We enabled the verbose debug output. Meaning It will display the output for each action it performs. It’s very helpful in case of failure. It will display the detailed failure message with cause. Which make debugging the code easy.

$mail->isSMTP();

It is used to set the mailer to use SMTP. Meaning the message/mail will be transferred via SMT Protocol. You can refer the class.phpmailer.php for more information.

$mail->Host = ‘smtp.gmail.com’;

As we are using Gmail to send email, we need to provide the smtp endpoint of Google gmail.

$mail->SMTPAuth = true;

$mail->Username = ‘YOUREMAIL@gmail.com’;

$mail->Password = ‘****’;

For obvious reason you need to authenticate your smtp email request with valid username and password. So we set the Auth to true and provided our username and password.

$mail->SMTPSecure = ‘ssl’;

$mail->Port = 465;

Gmail work on secure layer you can choose either SSL or TLS. We are going with SSL and Gmail listens on the port 465 for SSL connection requests.

You may need to change the Port and SMTPSecure while using the solution for your domain’s email address. You can also use SMTPSecure = FALSE and Port = 25 if your mail server doesn’t support secure connection.

$mail->addAddress(‘info@example.com’, ‘NAME’);

addAddress is the function where you can specify the email address of the receiver. The function takes two arguments. The first is the email address of the receiver and the second is the name of receiver.

$mail->addReplyTo(‘YOUR-PREFERED-REPLY-TO-EMAIL@gmail.com’, ‘Information’);

This will be the email address which receives the reply when the receiver hit the reply button. In some cases the replyto address is being ignored. Place it before the setFrom method and it may solve the issue.

$mail->setFrom(YOUREMAIL@gmail.com’, ‘YOUR-NAME);

What you want to show as your name and email when your receiver receives an email from your. Providing your real email and name is standard practice.

$mail->isHTML(true);

The option is to set if you are sending the email as html or plain text. When you are using PHPMailer you may want to send the HTML formated emails. Keep the isHTML(true).

$mail->Subject = “ “

The option is to set the email subject.

$mail->Body = ‘This is the HTML message body in bold!‘;

The HTML supported mail body. Observe the tags we used in the body. You can be creative here and assigned a beautiful html email template here.

$mail->AltBody = “Text version of your email body”.

If incase the HTML format emails are not supported by the email client. We included the plain text version of mail body.

if(!$mail->send()) {…}

The function $mail->send() is used the send the email. The function returns the boolean value.        If for some reason the email can not be sent, the function returns the error information as well.

Configuring solution for other email server:

You can use PHPMailer to send email from your branded email server. You may need to change some properties, but the overall process remains the same.

You better search for SSL/TSL SMTP ports your web hosting supports. And the host name for your email server.

You may need to alter the Host, SMTPSecure, Port, setFrom, and addReplyTo properties to match your mail server and hosting configurations. And obviously the username and password properties will change when you migrate from gmail to your email server.

If you are on CPanel based shared hosting and after making all the changes you see an error message saying “We do not authorize the use of this system to transport unsolicited 220 and/or bulk e-mail”. Here is the CPanel thread that may help you rectify the issue.

The complete code would like this:

require ‘vendor/autoload.php’;

$mail = new PHPMailer;

$mail->SMTPDebug = 3;                                   // 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 = ‘YourGmailAddress@gmail.com’;         // SMTP username

$mail->Password = ‘****’;                               // SMTP password

$mail->SMTPSecure = TRUE;                               // Enable TLS encryption, `ssl` also accepted

$mail->Port = 465;                                      // TCP port to connect to

$mail->addAddress(‘ToEmailAddress@mail.com’, ‘Name’);     // Add a recipient

$mail->addReplyTo(‘PreferedReplyEmail@mail.com’, ‘Name’);

$mail->setFrom(‘FromEmail@mail.com’, ‘Name’);

$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = ‘Here is the subject’;

$mail->Body    = ‘This is the HTML message body in bold!‘;

$mail->AltBody = ‘This is the body in plain text for non-HTML mail clients’;

if(!$mail->send()) {

echo ‘Message could not be sent.’;

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

} else {

echo ‘Message has been sent’;

}

Conclusion:

When you need a to send a well formated, attachment based email from any hosting platform PHPMailer would be a good alternet. The minimalistic footprint makes the Mail an easy task. Make sure you are using the latest version of library.

Author Bio:

Darshan is the founder of AlphansoTech a custom WordPress development company. You may find him writing detailed web technology related articles. Codeigniter 4 and WordPress are his latest interest. You can connect with him on LinkedIn and Twitter.