Search code examples
phpemailsslphpmailerstarttls

SMTP Connection fails with TLS activated


I am using the PHPMailer to send E-Mails to my customers. I want to send them using SSL/TLS, but this doesn't work. I am using an original example script from PHPMailer. When I comment this line: $mail->SMTPSecure = 'tls'; and change the credentials to my non ssl SMTP it works fine. Otherwise I get this error:

"Message was not sent.Mailer error: SMTP connect() failed."

I googled already and found similar problems where uncommenting ;extension=php_openssl.dll this line in the php.ini helped. But uncommenting this doesn't help me and I checked with phpinfo() that openssl is already enabled, so it should work or ? This is what I see at my phpinfo(): http://puu.sh/fyg5Z/a1ab5b0ea5.png

My used example (ofc with my own smtp credentials):

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                    // TCP port to connect to

$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
?>

How can I fix it? I tested the SMTP TLS connection with my email client thunderbird, which worked fine.


Solution

  • I found the answer in the closed issues section of the phpmailer github. I will quote the developer Synchro:

    You can't use ssl with port 587. The only combinations that will work are tls/587 and ssl/465, but you should use TLS. It doesn't make any differnce if you site uses http or https.