phpmailer發郵件提示SMTP->ERROR: Failed to connect to server的解決方法
使用phpmailer外掛發郵件失敗提示:SMTP -> ERROR: Failed to connect to server: Connection timed out (110) The following From address failed: [email protected] Mailer Error: The following From address failed: [email protected]
連線伺服器失敗:連線超時(110)
在本地(windows)測試的時候一切正常,一發到伺服器(centos)上就提示以上錯誤了。本地正常說明使用者名稱,密碼都沒錯,設定也沒錯,是伺服器的設定問題。到網上找了好久,都沒找到可行的方法。
我是用gmail的服務,包括在iptables中新增465埠,關閉iptables,關閉selinux 都不行。測試了php函式fopen,fsockopen,pfscockopen都正常。期間還使用163郵箱測了下,同樣提示以上錯誤。
後面查啊查,查到了一個貼子,http://drupal.org/node/805834 看13樓,大意是說可能是系統開啟了ipv6,而php至少在v5.3.2版本前,在處理ipv6上有些已知的bug......如果是這種情況,可以把smtp的伺服器直接設定成ipv4地址.....
所以來排查下。(如果你趕時間的話,直接拖到下文解決方法設定上試下吧。)
1.看下是否開啟了ipv6
$ ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:16:3B:E8:F5:26
inet addr:216.24.198.11 Bcast:216.24.198.127 Mask:255.255.255.128
inet6 addr: fe80::216:3eff:fee8:f226/64 Scope:Link
inet6 addr: 2604:6600:5::5769:54ef/64 Scope:Global
看inet6 addr說明開啟了支援ipv6
2.連線下gmail的smtp看是否能連線上,gmail的smtp的埠是 465
2.1 telnet 下
$telnet smtp.gmail.com 465
提示找不到telnet命令。
2.2 檢視下是否安裝了telnet
$rpm -qa|grep telnet
2.3 什麼都沒提示,說明沒有安裝。telnet有服務端和客戶端,缺少哪個安裝哪個。直接yum。
#yum -y install telnet
安裝服務端
#yum -y install telnet-server
2.4 安裝成功後編輯/etc/xinetd.d/telnet
# vi /etc/xinetd.d/telnet
把
disable = yes
改成
disable = no
2.5 開啟xinetd
#service xinetd start
2.6 測試連線本地
$ telnet localhost
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
..
連線正常
2.7 連線gmail 的smtp 埠是 465
$ telnet smtp.gmail.com 465
Trying 2607:f8b0:400e:c00::6d...
有類似這麼一串2607:f8b0:400e:c00::6d 的話說明連的是ipv6,一直卡著連不上。
2.8 ping 下gmail的smtp,找到它的ipv4
$ ping smtp.gmail.com
PING gmail-smtp-msa.l.google.com (74.125.141.108) 56(84) bytes of data.
64 bytes from da-in-f108.1e100.net (74.125.141.108): icmp_seq=1 ttl=50 time=33.5 ms
74.125.141.108 就是它的ipv4地址
2.9 telnet 到ipv4上看下
$ telnet 74.125.141.108 465
Trying 74.125.141.108...
Connected to 74.125.141.108.
Escape character is '^]'.
出現以上這些表示可連線上。看來是預設連線到ipv6的地址上了。
3.解決方法
其中一個方法是禁用伺服器的ipv6。其實更好的方法是在傳送郵件的程式碼裡把smtp的地址設定為ipv4,如下:
1 |
$mail ->Host
= "173.194.79.108" ; //
sets GMAIL as the SMTP server smtp.gmail.com
|
然後我測試傳送了一下,成功!
所以,提示Failed to connect to server: Connection timed out (110)
The following From address failed郵件發不了的問題之一可能是因為ipv6連線不上導致的。也跟php沒什麼關係,不是php的bug,因為我們這連線測試用talnet連線的,一樣優先連線到的是ipv6,不是php中使用程式碼連的。
4.telnet 不太安全,所以測完把它給禁掉,以後有需要再開啟
#vi /etc/xinetd.d/telnet
把
disable = no
改成
disable = yes
停止服務
# service xinetd stop
5.附上gmail中使用phpmailer發郵件的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php
include ( "mailsender/class.phpmailer.php" );
|