Simple & Quick PHPMailer SMTP Test PHP Script with Debugging

This is a simple quick PHP script for testing PHPMailer/SMTP to send email.

The code can be used either directly by command line or through your web browser with debug output enabled so you can see any potential error messages.

Also, this example uses a secure SSL connection.

PHPMailer SMTP

Easiest PHPMailer set up IMHO is to just download the three raw PHPMailer files from ‘here‘, (Exception.php, PHPMailer.php &  SMTP.php). Then use below code.

Note that the php files need to be in a web-readable folder if you want to see the debug messages in your web browser.

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once('/home/public_html/phpmailer/Exception.php');
require_once('/home/public_html/phpmailer/PHPMailer.php');
require_once('/home/public_html/phpmailer/SMTP.php');

$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Host = 'smtp.servername.com';
$mail->Port = 587; // usually either 465, 587, 25
$mail->SMTPAuth = true;
$mail->Username = 'user@email.com';
$mail->Password = 'password';
$mail->setFrom('from@email.com');
$mail->addAddress('to@email.com');
$mail->Subject = 'Email subject';
$mail->Body = 'Email body';
$mail->send();

$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => false
)
);

if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>

If the SMTP server is not using TLS encrytion try this instead:

$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

The SMTPOptions is optional and insecure but can be used as a quick fix if the SSL certificate cannot be verified because of an error message.

Which is usually something like this:

Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [/home/public_html/phpmailer/SMTP.php line 469]

Or if the SSL is self-signed you need to set that to true.

Also, the troubleshooting page is very useful.

At the time of writing latest PHPMailer version is 6.4.0 (the one I used with this).

Hope that helps, comments welcome.

Do come again, David.

Leave a Comment