Using the PHPMailer library to send messages via SMTP

Last modified: Tuesday November 21st, 2023

This article describes how to send messages via SMTP using the PHPMailer library.

Introduction

Incorporating an SMTP library into your application demands proficiency in PHP programming. If you are uncertain about how to integrate the sample script provided in this tutorial into your PHP application, it is advisable to seek the assistance of a skilled and trained PHP developer who can handle the task on your behalf.

When your application requires sending emails, you have two primary choices:

  1. Use PHP’s mail() function
  2. Use an SMTP library

The benefit of utilizing PHP’s mail() function lies in its extreme simplicity and user-friendliness. Nonetheless, there are a couple of disadvantages associated with using the mail() function:

  1. Email providers based on Microsoft platforms categorize messages generated using PHP mail() as spam because they do not recognize the DKIM headers generated by PHP’s mail().
  2. The mail() function operates synchronously, necessitating the application to pause until the SMTP transaction is finished before performing any other tasks.

When using an SMTP library like PHPMailer, you won’t encounter these same limitations, although it does involve a bit more configuration.

Procedure

The objective of this tutorial is to streamline the setup of the PHPMailer library, making it a quick and straightforward process.

Command Line Method (Recommended)

NOTE: Please replace cpanelusername with the username of your cPanel user, and replace domain.tld with your domain name.

  1. Login via Terminal or SSH as the cPanel user
  2. Navigate to the subdirectory where the script should exist:
    Bash:
    $ mkdir /home/cpanelusername/PHPMailerTest$ cd /home/cpanelusername/PHPMailerTest
  3. Clone the PHPMailer Library into place with the git clone command:
    $ git clone https://github.com/PHPMailer/PHPMailer
    Cloning into 'PHPMailer'...
    remote: Enumerating objects: 37, done.
    remote: Counting objects: 100% (37/37), done.
    remote: Compressing objects: 100% (26/26), done.
    remote: Total 6846 (delta 18), reused 25 (delta 11), pack-reused 6809
    Receiving objects: 100% (6846/6846), 4.79 MiB | 6.68 MiB/s, done.
    Resolving deltas: 100% (4438/4438), done.
  4. Review the documentation here: PHPMailer Documentation on Github
  5. Create the script by copying the example script provided later in this guide into the following file:
    /home/cpanelusername/PHPMailerTest/testScript.php
  6. Update the script with your own customizations.
  7. Test the script with the following command:
    $ php /home/cpanelusername/PHPMailerTest/testScript.php

File Manager Method

While the command-line method is the preferred option, you can employ this method if your hosting provider doesn’t grant access to SSH or lacks the Terminal icon.

NOTE: This approach necessitates placing the script in a server location that is publicly accessible. This may present a security risk and is advised only if the file is safeguarded by measures such as the Directory Privacy feature. Typically, this approach is employed during the testing phase. Once testing is finalized, you should relocate your mailer script to a secured location and subsequently invoke it from your PHP application. If you are uncertain about how to invoke the script from your PHP application, we recommend seeking assistance from a PHP developer.

  1. Login to the cPanel account for your user.
  2. Setup Directory Privacy for your “public_html” folder.
  3. Under the Files section, look for the “File Manager” icon.
  4. Click on the “public_html” directory to open it.
  5. Download the PHPMailer library as a zip file: PHPMailer on Github
  6. Upload the zip file into the FileManager with the “Upload” button from the horizontal menu near the top.
  7. Use the “Extract” button in the horizontal menu of the File Manager to extract the PHPMailer library.
  8. Create a new PHP file called “test.php” in the “public_html” directory with the contents of the example script below.
  9. Update the script with your own customizations.
  10. Test the script by visiting the URL to the file: https://domain.tld/test.php

Example Script

Technical Support does not provide assistance with the implementation, debugging, or maintenance of the script in this tutorial. If you encounter errors with your script, please take a look at our How to debug PHPMailer if you see “SMTP Error: Could not authenticate.” page for further assistance.
The provided example script is an excellent starting point, designed to work seamlessly with PHPMailer 6.1.2. This script uses required statements to include the three essential PHP files that PHPMailer needs to function in the most basic manner.

This script is set up to produce detailed debug output by default. The script requires modification in order to work in your specific environment. You must update the following:

  • The paths to the PHP files in the required statements
  • $mail->Host – Use your cPanel server’s hostname. Your domain name can be used in some cases as well.
  • $mail->Username – Use the email address of a valid email account on your cPanel server.
  • $mail->Password – Use the password for the valid email account on your cPanel server.
  • $mail->setFrom – Use the same address from the Username configuration above.
  • $mail->addAddress – Set this to the recipient’s address.
  • $mail->addReplyTo – Set this to the same address from the Username configuration above.
  • $mail->addCC – Remove this or set it to a CC recipient address.
  • $mail->addBCC – Remove this or set it to a BCC recipient address.
  • $mail->addAttachment – Remove this or update the path to a file to attach.
  • $mail->Subject – Update this to your desired subject.
  • $mail->Body – Update this to your desired HTML content. This does not have to be HTML but it can contain HTML.
  • $mail->AltBody – Update this to a plain text version of your content/message.
Code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '/home/cpanelusername/PHPMailerTest/PHPMailer/src/Exception.php';
require '/home/cpanelusername/PHPMailerTest/PHPMailer/src/PHPMailer.php';
require '/home/cpanelusername/PHPMailerTest/PHPMailer/src/SMTP.php';

// Instantiation and passing [ICODE]true[/ICODE] enables exceptions
$mail = new PHPMailer(true);

try {
 //Server settings
 $mail->SMTPDebug = 2; // Enable verbose debug output
 $mail->isSMTP(); // Set mailer to use SMTP
 $mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
 $mail->SMTPAuth = true; // Enable SMTP authentication
 $mail->Username = 'user@example.com'; // SMTP username
 $mail->Password = 'secret'; // SMTP password
 $mail->SMTPSecure = 'tls'; // Enable TLS encryption, [ICODE]ssl[/ICODE] also accepted
 $mail->Port = 587; // TCP port to connect to

//Recipients
 $mail->setFrom('from@example.com', 'Mailer');
 $mail->addAddress('recipient1@example.net', 'Joe User'); // Add a recipient
 $mail->addAddress('recipient2@example.com'); // Name is optional
 $mail->addReplyTo('info@example.com', 'Information');
 $mail->addCC('cc@example.com');
 $mail->addBCC('bcc@example.com');

// Attachments
 $mail->addAttachment('/home/cpanelusername/attachment.txt'); // Add attachments
 $mail->addAttachment('/home/cpanelusername/image.jpg', 'new.jpg'); // Optional name

// Content
 $mail->isHTML(true); // Set email format to HTML
 $mail->Subject = 'Here is the subject';
 $mail->Body = 'This is the HTML message body <b>in bold!</b>';
 $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();
 echo 'Message has been sent';

} catch (Exception $e) {
 echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Was this article helpful?
Views: 358

10 Years Beehosting!
Celebrate with 70% OFF + FREE Site Transfer.

Beehosting.pro website uses cookies

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners who may combine it with other information that you’ve provided to them or that they’ve collected from your use of their services.

Menu