Posted in PHP & MySQL Server

PHP – How to Setup PHPMailer and Send Email using SMTP

PHP – How to Setup PHPMailer and Send Email using SMTP Posted on May 11, 2020Leave a comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Are you using mail() function of PHP to send an email ? but your emails message are going to Spam folder, or you need advance customization during sending emails? I suggest you should use the PHPMailer class. It is a full-featured email creation and transfer class for PHP. To setup it on your PHP code, do step by step method mentioned below:

Get SMTP Authentication Credentials:

Step 1: Be sure you have configured your server to authenticate properly with the receiver. View my previous article to configure your server: Server Level Optimization to Avoid Spam Filter on Email Sent from SMTP

Step 2: Get the SMTP authentication credentials. Go to your cPanel, and create a new email account. Note down its username and password. On the email list, you will see “CONNECT DEVICES”, click on it to get SMTP, IMAP, and POP3 information.

connect devices

When you click on “CONNECT DEVICES”, you will get the following information:

Email information

Information on the blue panel is to authenticate using secure mode and on the orange panel is non-secure mode. I recommend the secure SSL/TLS setting to authenticate with the SMTP server.

Note down the following information:

  • Username
  • Password: Email account password you set during creating it.
  • Outgoing Server Address
  • SMTP Port

Download PHPMailer at Project Directory:

Step 3: Download PHPMailer using Composer by following command on your PHP project directory.

If you haven’t installed Composer in your machine then install composer first. I have written an article previously for Linus users: How to Install Composer in Ubuntu 20.04 LTS (Focal Fossa)

composer require phpmailer/phpmailer

This command downloads the PHPMailer class in your PHP project folder. It will create the following directory.

  • vendor/
  • —— autoload.php
  • —— phpmailer/
  • —— composer/

Setup PHPMailer:

Replace the authentication credentials and use the PHP code below:

<?php
// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load autoloader file downloaded by composer
require 'vendor/autoload.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

//SMTP authenciation credientials:
$username = '[email protected]';
$password = '[email protected]#';
$smtphost = 'mail.hellohpc.com';
$port = '465';
//replace this information


//email body
$subject = "Subject fo the email";
$htmlmail = "<h1>Your html email content</h1>";
$althtmlmail = strip_tags($htmlmail);
//replace this email body

// for SSL/TSL port 465
$smtpsecure = PHPMailer::ENCRYPTION_SMTPS;
// use  PHPMailer::ENCRYPTION_STARTTLS
// for Non-SSL port 26

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
    $mail->isSMTP(); // Send using SMTP
    $mail->Host       = $smtphost;// Set the SMTP server to send through
    $mail->SMTPAuth   = true; // Enable SMTP authentication
    $mail->Username   = $username; // SMTP username
    $mail->Password   = $password; // SMTP password
    $mail->SMTPSecure = $smtpsecure; // Enable TLS encryption
    $mail->Port       = $port; // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer'); //set the sent from information
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
    $mail->addAddress('[email protected]');// Name is optional
    $mail->addReplyTo('[email protected]', 'Information');

    //otpional attributes
    $mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

    // Optional attributes if you want to attache Attachments
    $mail->addAttachment('/files/file.zip');// Add attachments
    $mail->addAttachment('/files/image.jpg', 'new.jpg'); // Optional name

    // Content
    $mail->isHTML(true);  // Set email format to HTML
    $mail->Subject = $subject; //subject fo the email
    $mail->Body    = $htmlmail; //mail content
    $mail->AltBody = $althtmlmail;

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

//customize this code according to your features.
?>

In this way, you can setup the PHPMailer with your PHP code and send emails more authentically. If you get any problem during setup then comment down, I will try to sort it out for you.

You can view more about PHPMailer at: https://github.com/PHPMailer/PHPMailer

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Leave a Reply

Your email address will not be published. Required fields are marked *