使用 PHP 寄信經常會使用 PHPMailer,但是要使用內部網路的 Mail
Server 來寄信,卻一直遇到如下述的錯誤:
Warning: stream_socket_enable_crypto(): SSL operation failed with code 1.
OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
要怎麼解決呢?
PHP 使用 PHPMailer 遇到 SSL operation failed 的解法
PHPMailer 常見的寫法如下:(註:設定 From、To、Subject、Body.. 在此就不寫了)
- <?php
- $mail = new PHPMailer(true);
- $mail->isSMTP();
- $mail->Host = 'relay-hosting.secureserver.net';
- $mail->SMTPAuth = true;
- $mail->Username = 'user@example.com';
- $mail->SMTPSecure = 'tls';
- ?>
現在已經很習慣使用 SMTPSecure 為 tls 或 ssl,但是臨時自己架設的 Mail Server,沒有設定憑證、帳號、密碼,修改範例如下:
- <?php
- $mail = new PHPMailer(true);
- $mail->SMTPDebug = 2; // Enable verbose debug output (print debug message)
- $mail->isSMTP();
- $mail->Host = 'relay-hosting.secureserver.net';
- $mail->Port = 25;
- $mail->SMTPAuth = false;
- $mail->SMTPSecure = false;
- ?>
將 SMTPAuth、SMTPSecure 都設定 false,發信卻還是發生「SSL operation failed」、「certificate verify failed」的問題,要怎麼解決呢?
PHPMailer 遇到問題時,官方網頁有疑難排解可以參考:Troubleshooting · PHPMailer/PHPMailer Wiki
- 文章找到這個參數:$mail->SMTPAutoTLS = false;
原來現在 PHPMailer 已經預設啟用 TLS,所以程式修改如下:
- <?php
- $mail = new PHPMailer(true);
- $mail->SMTPDebug = 2;
- $mail->isSMTP();
- $mail->Host = 'relay-hosting.secureserver.net';
- $mail->Port = 25;
- $mail->SMTPAuth = false;
- $mail->SMTPSecure = false;
- $mail->SMTPAutoTLS = false;
- ?>
於是就可以使用自己架設的 Mail Server 正常寄信囉~