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 2mhost hosting account 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 inside PHP tags, use your real information (mail server, user name, password, ..etc) and save the file.

<?php
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP; 
use PHPMailer\PHPMailer\Exception; 

$mail = new PHPMailer(true); 

try { 
      $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; 

      $mail->setFrom('user@yourdomain.com', 'Your name'); 
      $mail->addAddress('recipient@gmail.com', 'User name');
      $mail->addReplyTo('user@yourdomain.com', 'Your name'); 

      $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: Oct 26, 2025 11:24