I am having some sort of weird behavior with the following script. I am using PHPMailer to send emails using the SMTP method through using my OVH email box. My script is hosted on my OVH website.
The script returns the "Error #2: stream_socket_client(): Failed to enable crypto" (see full error below) about 60% of the time. The other 40% of the time, the script works and the email is received as intended.
When used locally (localhost), the script works 100% of the time.
I have configured DKIM & SPF under my DNS records on OVH (and checked that they worked using mail-tester.com). I have tried using tls or starttls with port 587 and the issue remains.
I have contacted OVH and they can't see any error on their side.
Would anyone have any idea to fix the issue? It seems to me the issue comes from the connection to the smtp server on OVH (as it works perfectly locally) but I can't figure out how to fix this.
Thank you in advance for the help!!
This is the full error:
Connection: opening to ssl://ssl0.ovh.net:465, timeout=300, options=array()
Connection failed. Error #2: stream_socket_client(): SSL: Success [/XXX/PHPMailer-master/src/SMTP.php line 408]
Connection failed. Error #2: stream_socket_client(): Failed to enable crypto [/XXX/PHPMailer-master/src/SMTP.php line 408]
Connection failed. Error #2: stream_socket_client(): Unable to connect to ssl://ssl0.ovh.net:465 (Unknown error) [/XXX/PHPMailer-master/src/SMTP.php line 408]
SMTP ERROR: Failed to connect to server: (0)
SMTP Error: Could not connect to SMTP host. Failed to connect to server
And this is my script:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
$mail = new PHPMailer(true);
$email = "[email protected]";
$to = $email;
$subject = "Test";
$message = "
<html>
<body>
<h1>test email !</h1>
</body>
</html>
";
$mail->Host = 'ssl0.ovh.net';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->Username = 'hidden for stackoverflow';
$mail->Password = 'hidden for stackoverflow';
$mail->isSMTP();
$mail->CharSet = 'UTF-8';
$mail->addCustomHeader('MIME-Version: 1.0');
$mail->addCustomHeader('Content-type:text/html;charset=UTF-8');
$mail->isHTML(true);
$mail->setFrom('hidden for stackoverflow', 'hidden for stackoverflow');
$mail->addReplyTo('hidden for stackoverflow', 'hidden for stackoverflow');
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->SMTPDebug = 4;
if (!$mail->send()) {
echo 'Email not sent an error was encountered: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
Output:
contacting OVH
adding DKIM & SPF
trying locally
using tls or starttls with port 587
resetting SSL certificate