PHPMailer Pro, a short tutorial

by Andy Prevost

Friday February 9 2024

A few assumptions to start. Your installation would have PHPMailer Pro installed off the root of your project as in:

– assets
– assets/lib
– assets/lib/PHPMailer.Pro.php

Using any PHP class starts with loading it. For PHPMailer Pro, that would be:

require "assets/lib/PHPMailer.Pro.php";

Next we have to start it. Since PHPMailer Pro has a namespace, we have to include that:

$mail = new codeworxtech\PHPMailerPro\PHPMailerPro();

In its most minimal possible use, all you need to add is the Recipient, a Subject, and a Message. That could be as simple as:

$mail->subject = "Test Subject";
$mail->AddRecipient = ["name@example.com" => "Recipient Name"];
$mail->messageHTML = "<p>A simple HTML message</p>";

All we need to do now is send it. By default, PHPMailer Pro sends using SMTP as the transport. Since there is no SMTP username or password above, that would send SMTP un-authenticated with:

$mail->Send();

If we wanted to over-ride the default, we could send via Sendmail or IMAP with one of these commands:

$mail->Send('sendmail');

or

$mail->Send('imap');

Why isn't the sender, reply to or return path shown? You can include those if you wish. In the minimalist version above, we are accepting to send with the Sender name as "No Reply" and the email address as "noreply@" and the domain name of the site.

You can also alter just the default name/email by changing:

$mail->senderName = "Joe Smith";
$mail->senderEmail = "joe.smith@example.com";

or

$mail->SetSender(["joe.smith@example.com" => "Joe Smith"]);

The square brackets, by the way, is PHP's short cut for defining an array. You could also use:

$mail->SetSender(array("joe.smith@example.com" => "Joe Smith"));

Note that when using SMTP in the example above, we did not have to specify the SMTP host name, the port, or any other special invoking commands. PHPMailer Pro will identify the server and port number before sending. Nothing is required to use SMTP as the transport. 

PHPMailer Pro has three possible transport methods. Those are SMTP, Sendmail, and IMAP. It's automatic and in that order. PHPMailer Pro will try SMTP first. If SMTP is not available for use, PHPMailer Pro will then attempt to send using Sendmail as the transport. And if Sendmail is not available, PHPMailer Pro will use IMAP. Of course, if IMAP is not available, PHPMailer Pro will fail and provide an appropriate error message.

The complete code for our minimal test is below.

require "assets/lib/PHPMailer.Pro.php";
$mail = new codeworxtech\PHPMailerPro\PHPMailerPro();
$mail->subject = "Test Subject";
$mail->AddRecipient = ["name@example.com" => "Recipient Name"];
$mail->messageHTML = "<p>A simple HTML message</p>";
$mail->Send();

For more examples, visit https://PHPMailer.Pro examples page.

 

◀ Previous Next ▶

Post a Comment