Web Hosting Knowledge Base / Hosting and Websites

How to setup PHPMailer to send e-mail via SMTP in cPanel hosting?

It's a common mistake to use PHP native mail() function to send e-mail, it looks easy but in reality, it will not deliver e-mail. The message's header generated by mail() will not make the message relayed by the server or accepted by major mail providers like Gmail, it will be considered spam and will be discarded.

In this tutorial we will use PHPMailer library to send a test message, you can then integrate the code with your own application. Using SMTP to send email will ensure that message will have the proper authentication headers for successful delivery.

1. Create a mailbox @yourdomain.com, or use any existing mailbox @yourdomain, we will use this address for SMTP authentication.

2. Login your website via Terminal or SSH (use your domain name as server with your cPanel logins and port 5555)

3. Create a test folder inside your public_html, and switch to it:

cd public_html mkdir test cd test

4. Clone PHPMailer repository

git clone https://github.com/PHPMailer/PHPMailer

5. Create the test file

nano test.php

6. Copy/Paste the following code, use your real information (mail server, user name, password, ..etc) and save the file.

<?php //remember to replace 'yourusername' with your cpanel/FTP user name //and replace 'yourdomain.com' with your actual domain name. use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require '/home/yourusername/public_html/test/PHPMailer/src/Exception.php'; require '/home/yourusername/public_html/test/PHPMailer/src/PHPMailer.php'; require '/home/yourusername/public_html/test/PHPMailer/src/SMTP.php'; $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = 2; $mail->isSMTP(); $mail->Host = 'mail.yourdomain.com'; $mail->SMTPAuth = true; $mail->Username = 'user@yourdomain.com'; // Your email address $mail->Password = 'password'; //email box password $mail->SMTPSecure = 'tls'; $mail->Port = 587; //Recipients $mail->setFrom('user@yourdomain.com', 'Your name'); $mail->addAddress('recipient@gmail.com', 'User name'); // The recipient $mail->addReplyTo('user@yourdomain.com', 'Your name'); // Content $mail->isHTML(true); $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'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; }

7. run the file from the browser: yourdomain.com/test/test.php

Last update: Feb 27, 2023 17:31