Send Email In PHP Using PHPMailer

PHPMailer is a PHP class that enables dependable email functionality from PHP, including SMTP. The fastest (but definitely not most lightweight!) way to get running is as follows.

Clone the Git Repository to your project’s folder:

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

My example project is named send-email.php and after cloning the repository, a list of the folder contents reveals this hierarchy:

 $ ls
PHPMailer  send-email.php

send-email.php has the following code, which is a modified version of an example in the repository’s README file. I’ve configured this code to email from a G Suite / Gmail account with 2-step verification, so I configured an app-specific password for the script. You could also use OAuth.

 

//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require('PHPMailer/src/PHPMailer.php');
require('PHPMailer/src/SMTP.php');


$content = 'Dear Reader, 

This is an email from PHPMailer. <strong>HTML tags are supported!</strong>';

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port     = 587;  


$mail->Username = "example@gmail.com"; //Google username -- full email address
$mail->Password = "fjkwjfqpfjshfodt"; //App-specific password (This is a fake. Switch it to yours.)

$mail->Host     = "smtp.gmail.com";
$mail->Mailer   = "smtp";

//The email sender and reply-to info.
//These usually should match your $mail->Username details on line 19
$mail->SetFrom("example@gmail.com", "John Example");
$mail->AddReplyTo("example@gmail.com", "John Example");

//Add recipients
$mail->AddAddress('recipient@example.com');
$mail->AddAddress('jen@acme.com');

//Your desired subject
$mail->Subject = "Test email using PHP mailer";

$mail->WordWrap   = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);
if(!$mail->Send()) 
echo "Problem sending email.";
else 
echo "email sent.";