[FIXED] PHPMailer and SMTP with SSL issues

If you’re using PHPMailer library for sending emails and have some issues with SMTP – there are some steps to check.

Step one: use SMTP :)

From my experience I can say that’s quite common mistake. Make sure your code have this line:


$phpmailer->isSMTP();

Step two: turn SMTP debugging on

Using SMTP allows you to debug sending process more efficient. You can even trace whole communication between mail servers. To do this you need to just enable it with setting SMTPDebug property.

In documentation you can find 5 levels available:

Constant name Constant value Meaning
SMTP::DEBUG_OFF 0 Default value. No debugging.
SMTP::DEBUG_CLIENT 1 Contains only output messages sent by the client.
SMTP::DEBUG_SERVER 2 same as one – but also with responses  from the server
SMTP::DEBUG_CONNECTION 3 same as two, but contains more detailed information
SMTP::DEBUG_LOWLEVEL 4 the most rich in the information/details level

Mostly I’m using level two (basic client/server communication), you can use it like this:


$phpmailer->SMTPDebug = 2; // or:
$phpmailer->SMTPDebug = SMTP::DEBUG_SERVER;
// after sending an email
print $phpmailer->ErrorInfo;

This should helps you find all issues with using SMTP protocol.

Step three: check for openssl support

To send mails through SMTP with PHP you need to have SSL support. To check that just run that code:


if (extension_loaded('openssl')) {
  print 'openssl extension loaded.';
}

You can also use phpinfo() to get more details about installed extension.

In case you don’t have openssl installed – you need to install it manually. I will wrote about it in separate post.

Step four: ignore certificate checking

I cannot recommend it, but…

Yeah. Security is important, but sometimes you just need to send that email. If your server is not properly configured – you can bypass some security checks. Just update your script’s config with:


$phpmailer->SMTPOptions = [
  'ssl' => [
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
  ]
];

Basically it will ignore verification process for peers and accept self signed certificates. More in SSL Context documentation.

Step five: check firewall and target server

Because it’s not always about you.

SMTP service you trying to connect to can be unavailable. Or just broken. You can check this using the telnet tool:


telnet smtp.gmail.com 587

To check your server capabilities/ports you can use valid external server, for example:

$phpmailer->Port = 25;
$phpmailer->Host = 'relay-hosting.secureserver.net';
$phpmailer->SMTPAuth = false;
$phpmailer->SMTPSecure = false;

Summary

Basically I can highly recommend you to use SMPT with PHPMailer. In case of any issue you have some ways to fix it. Debugging is better than for standard mail() function, also we can easily handle untrusted SSL certificates just by… ignoring them (it may be not the best option here…).