Graph and PowerShell Blog | About | Links
Installing and configuring PHPMailer
25-Jun-24

PHPMailer has several advantages over the built-in mail() function, most importantly for me is the ability to call attached images inline in the mail body.

While I primarily use PowerShell for mail-sending scripts, it's always a good idea to have a backup and it's fun to learn new tricks.

The preferred method for installing is to use Composer, but unfortunately, I couldn't use this as it doesn't support an authenticated web proxy. The other way to install is to download a Zip file, which should be unpacked to the PHP web root, so with IIS this is typically c:\inetpub\wwwroot\.

Rename the folder to PHPMailer if not already called that, then create a script that calls the function and sends a mail:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require './PHPMailer/src/Exception.php';
require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';

$auth = base64_encode('service_account:password);

$context = stream_context_create([
'http' => [
'proxy' => 'tcp://webproxy.domain.local:8080',
'request_fulluri' => true,
'header' => "Proxy-Authorization: Basic {$auth}"
],
]);

$mail = new PHPMailer(true);

try {
//Server settings $mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'relay.domain.com';
$mail->SMTPAuth = false;
$mail->Port = 465;

//Recipients
$mail->setFrom('php@domain.com', 'PHP Mailer');
$mail->addAddress('user@domain.com', 'First Surname');
# $mail->addAddress('john@example.com');
# $mail->addReplyTo('info@example.com', 'Information');
# $mail->addCC('cc@example.com');
# $mail->addBCC('bcc@example.com');

//Attachments # $mail->addAttachment('c:/scripts/file.txt');
# $mail->addAttachment('c:/scripts/image.jpg', 'new.jpg');

//Content $mail->isHTML(true);
$mail->Subject = 'PHP test';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This email does not support 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}";
}

?>

You can either call the script from a web server request or test locally run from Command Prompt:

php c:\inetsrv\wwwroot\mailscript.php -r

* it's important that the -r switch is at the end