Menu
in , ,

The Best Way To Send Email Using PHP And PHPMailer, CLI.

PHPMailer

In this lab, we will talk about how to simply install PHPMailer Class and send your first email using PHP CLI.

This lab is a part of our simple monitor and updating system which we previously talked about when trying to send a telegram bot message, as we need to send an update notification/warning message to a specific team of colleagues.

In this lab we will:

  1. Install PHP
  2. Install PHP Composer
  3. Install PHPMailer Using Composer
  4. Coding A Simple PHP Script To Send Email
  5. Fire The PHP Script From CLI

Step1- Install PHP

Install PHP On Ubuntu Linux

It's a simple task to install PHP on Linux as on Ubuntu we can run the following commands:

  • Update Our system
# sudo apt update
# sudo apt upgrade
  • Install The PHP And Required Packages
# sudo apt install php php-common php-mbstring php-zip php-net-socket php-gd php-bcmath php-json php-curl php-intl php-soap php-xml php-xmlrpc unzip wget git curl sendmail

Install PHP On Centos Stream

When we are on Centos Stream, we can go as the following to install PHP:

  • Update Our System
# sudo dnf update
  • Install The PHP And Required Packages
# sudo dnf install php php-common php-mbstring php-zip php-gd php-bcmath php-json php-curl php-intl php-soap php-xml php-openssl unzip wget git curl sendmail

Install PHP On Windows

To install PHP, and all required packages on Windows, you can follow the step-by-step guide: A Simple Way To Installing PHP And Run Script Files On Windows.

Step2- Install PHP Composer

We can install PHP composer by running the following simple 3 commands to download and install it.

# curl -sS https://getcomposer.org/installer | php
# chmod +x composer.phar
# mv composer.phar /usr/local/bin/composer

And to install The PHP Composer on windows you can follow the same presented guide in the previous step.

Step3- Install PHPMailer Using Composer

Now we need to install PHPMailer class, we can get the source code from the PHPMailer GitHub page.

To install PHPMailer Using Composer we need to run the following command on Linux or in Windows Powershell/CMD terminal, as we make preparing for our windows before.

# composer require phpmailer/phpmailer

The output can be similar to

[root@localhost ~]# composer require phpmailer/phpmailer
Info from https://repo.packagist.org: #StandWithUkraine
Using version ^6.6 for phpmailer/phpmailer
./composer.json has been created
Running composer update phpmailer/phpmailer
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
  - Locking phpmailer/phpmailer (v6.6.4)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Downloading phpmailer/phpmailer (v6.6.4)
  - Installing phpmailer/phpmailer (v6.6.4): Extracting archive
5 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
1 package you are using is looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found

Step4- Coding The PHP Script To Send The Email

We need to import PHPMailer class to our namespace so we will start by use PHPMailer\PHPMailer\PHPMailer; and the Exception class.

If we download the PHPMailer source code and not using the Composer installation method, so we will need to pass the full absolute path of that class.

Remember that, if you saved your PHP script file at the same place where you installed PHPMailer, you will load the composer autoloader as  require 'vendor/autoload.php'; or you will need to pass the full absolute path to the autoloader.

// Use the PHPMailer Class 
use PHPMailer\PHPMailer\PHPMailer; 
use PHPMailer\PHPMailer\Exception; 

// Load Composer's autoloader 
require 'vendor/autoload.php'; 

// Sender and Email information
$senderEmail='sender.email@domain.xyz'; 
$senderName='Sender Name'; 
$replyTo='replyto.email@domain.xyz'; 
$subJect='RE : Subject'; 
$messageLetter='The Email Message Body'; 

// Target Email address
$emailTarget='target.email@domain.xyz'; 

// Buiding the email object attributes 
$mail = new PHPMailer; 
$mail->setFrom($senderEmail,$senderName);
$mail->addReplyTo($replyTo);
$mail->addAddress($emailTarget);
$mail->Subject = trim($subJect);
$mail->Body = $messageLetter;
// The Html Message Type, so message body can contain html tags.
$mail->IsHTML(true);
// Clean Body
$mail->AltBody =strip_tags($messageLetter);          
$mail->CharSet = 'UTF-8';
$mail->Encoding = '8bit';

// Fire your Email.          
if (!$mail->send()) {
    echo '[Error:]'.htmlspecialchars($mail->ErrorInfo);
}
else {
    echo '[Status:] Sent';
}

Now we can code our PHP script file and save it as sendemail.php.

Step5- Fire The PHP Script From CLI

To fire our email message we can run the command

# php -f sendemail.php

Step6- Avoid Email To Going To The Spam Folder Or Ignorance

To avoid your email from going to the spam folder or being rejected from the Mail servers/providers.

Using Our Private STMP Server

We will need to use a local or external SMTP server, and we can build our server by following the guide Build Your Email Server In 5 Simple Steps As A Professional With Free Tools.

After that, we can run our code smoothly if running on the same device, also we can add extra lines to connect with our SMTP.

And the same case if you used External SMTP ie. Gmail/Gsuite as shown next.

Using Gmail Outgoing Mail (SMTP) Server

The Gmail SMTP information needed is:

Server: smtp.gmail.com 
Requires SSL: Yes
Requires TLS: Yes (if available)
Requires Authentication: Yes 
Port for SSL: 465 
Port for TLS/STARTTLS: 587

For Google Gmail/Gsuite you will need to set up an application password to use for the SMPT authentication process while sending our email.

Creating Google Application Password

1- Go to your google account panel

Select the Security tab, from the menu, as shown in the below screenshot, then get into the App password settings.

2- Create your App Password

We need to select Other (Custom name), then name our application, and Generate our password.

 

The PHP script code now can be as the following

<?php
// Use the PHPMailer Class
use PHPMailer\PHPMailer\PHPMailer;

// Use SMTP
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

// Sender and Email information
$senderEmail='sender.email@gmail.com';
$senderName='Sender Name';
$replyTo='replyto.email@gmail.com';
$subJect='RE : please reply with the result';
$messageLetter='plese reply with the result';

// Target Email address
$emailTarget='target.email@domain.xyz';

// Buiding the email object attributes
$mail = new PHPMailer;

// SMTP Configuration

$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(true); //Send using SMTP
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'sender.email@gmail.com'; // SMTP username
$mail->Password = 'ciawupvmezekittr'; // The Google Application password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable implicit TLS encryption
$mail->Port = 587; //TCP port to connect to; 
$mail->SMTPKeepAlive = true;

// End Of SMTP Configuration


$mail->setFrom($senderEmail,$senderName);
$mail->addReplyTo($replyTo);
$mail->addAddress($emailTarget);
$mail->Subject = trim($subJect);
$mail->Body = $messageLetter;

// The Html Message Type, so message body can contain html tags.
$mail->IsHTML(true);

// Clean Body
$mail->AltBody =strip_tags($messageLetter);
$mail->CharSet = 'UTF-8';
$mail->Encoding = '8bit';

// Fire your Email.
if (!$mail->send()) {
echo '[Error:]'.htmlspecialchars($mail->ErrorInfo);
}
else {
echo '[Status:] Sent';
}

?>

Leave a Reply

Exit mobile version