Question
How to use the PHPMailer library to send messages via SMTP from my website?
Answer
If your application needs to send emails, you have two main options:
- Use PHP's
mail()function - Use an SMTP library, such as PHPMailer.
The advantage of using PHP's mail() function is that it is incredibly simple and easy to use. However, a major downside is that many email providers mark messages created with PHP mail() as spam, as the PHP mail() function does not perform proper authentication. As a result, headers such as the DKIM and features like "Sender Verify" may fail validation at the receiving server.
Using an SMTP library such as PHPMailer resolves this, but it requires a bit more setup.
Note: Many popular website builders, such as WordPress, Joomla, Drupal, and Magento, provide native features or plugins for using an SMTP Library. It is recommended that you review the available options for your website and choose one that meets your needs, with assistance from your System Administrator.
Warning: Manually integrating an SMTP library into your application requires expertise in PHP programming. If you are unsure how to integrate the example script from this tutorial into your PHP application, you must reach out to a PHP developer with the skills and training required to do so for you. The following is provided as an example for educational purposes.
- Log in via Terminal or SSH as the cPanel user
-
Create and navigate to the subdirectory where the script should exist:
# mkdir -v /home/cpanelusername/PHPMailerTest; cd /home/cpanelusername/PHPMailerTest
Note: Replace
cpanelusernamewith the username of your cPanel user. -
Clone the PHPMailer Library into place with the
git clonecommand:# git clone https://github.com/PHPMailer/PHPMailer
- Create the script by copying the Example Script in the 3rd tab to the following location:
/home/cpanelusername/PHPMailerTest/testScript.php - Configure the example script with the relevant SMTP information.
-
Test the script with the following command:
# php /home/cpanelusername/PHPMailerTest/testScript.php
Note: Replace
cpanelusernamewith the username of your cPanel user.
Note: This method requires you to place the script in a publicly accessible location on the server. This can pose a security risk and is recommended only if the file is protected by a feature such as Directory Privacy (link provided below). This would only be used during testing. After testing is complete, you would move your mailer script to a protected location and then call it from your PHP application. Please reach out to a PHP developer if you are unsure about how to call the script from your PHP application.
- Log in to the cPanel account for your user.
- Set up Directory Privacy for your public_html folder.
- Under the Files section, look for the File Manager icon.
- Click on the public_html directory to open it.
- Download the PHPMailer library as a zip file:
PHPMailer on Github - Upload the zip file into the File Manager with the Upload button from the horizontal menu near the top.
- Use the Extract button in the horizontal menu of the File Manager to extract the PHPMailer library.
- Create a new PHP file called test.php in the public_html directory with the contents of the example script from the 3rd tab: Example Script
- Configure the example script with the relevant SMTP information.
-
Test the script by visiting the URL to the file:
https://domain.tld/test.phpNote: Replace
domain.tldwith the actual domain.
Warning: cPanel Technical Support does not provide assistance with implementing, debugging, or maintaining the script in this tutorial. If you encounter errors with your script, please review the additional resources article for further assistance
The following example script is a good place to get started. It is compatible with PHPMailer 7.1.1. This example script uses require statements for the three 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 on your specific environment. You must update the following:
- The paths to the PHP files in the
requirestatements -
$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 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.
<?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}";
}
Additional Information
PHPMailer Documentation on Github
How to debug PHPMailer if you see "SMTP Error: Could not authenticate."
Comments
0 comments
Article is closed for comments.