2010-02-24 25 views
25

有沒有人知道我怎麼可以在PHP中捕獲郵件錯誤(在發送電子郵件時出現錯誤,錯誤是由郵件服務器造成的)?如何捕獲由mail()引起的錯誤?

,是由emailserver的下降造成的誤差不超過:

<!--2010-02-24T14:26:43+11:00 NOTICE (5): Unexpected Error: mail() [<a href='function.mail'>function.mail</a>]: Failed to connect to mailserver at "ip " port portip, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() (# 2).
2010-02-24 14:26:43
Username: admin
Error in line 439 of file D:\test.php
Script: /customer.php
[Global Error Handler]
-->

+1

你如何發送郵件?你是否直接與SMTP服務器通話? – 2010-02-24 03:24:22

回答

42

這大約是最好的,你可以這樣做:

if (!mail(...)) { 
    // Reschedule for later try or panic appropriately! 
} 

http://php.net/manual/en/function.mail.php

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

如果您需要壓制警告,您可以使用:

if ([email protected](...)) 

要小心使用@運營商沒有適當的檢查,以確定是否成功。


如果mail()錯誤並不可抑制(怪異,但現在不能測試它),你可以:

一)暫時關閉的錯誤:

$errLevel = error_reporting(E_ALL^E_NOTICE); // suppress NOTICEs 
mail(...); 
error_reporting($errLevel); // restore old error levels 

B)使用如fireMike所建議的另一個郵件程序。

如果mail()原來太脆弱和不靈活,我會研究b)。關閉錯誤會使調試變得更加困難,而且通常是不好的。

+3

+1好答案。很多時候人們會忘記'mail()'返回一個'bool'。很好,你提到「如果沒有錯誤,郵件到達」的假設,因爲這是新開發人員常見的誤解。 – Sampson 2010-02-24 03:27:15

+0

嗨,我知道郵件()將返回true或false。但不明原因,這總是在我的頁面上顯示錯誤消息(錯誤消息顯示在我上面的問題中,錯誤只能在查看頁面源代碼時查看): 並且此錯誤導致我無法將(頁眉())頁面重定向到新頁面。我有搜索代碼,但無法找出實際顯示此錯誤的地方。也許這是在php stmp設置中設置的? – 2010-02-24 22:02:20

+0

我的問題是...我怎麼能忽略或從我的頁面標題拋出「無法連接到郵件服務器」錯誤信息?有誰知道如何去做?我一直在谷歌搜索,但仍然無法找到解決方案 – 2010-02-24 22:28:28

1

您可以使用PEAR Mail類和方法,它允許您通過檢查錯誤:

if (PEAR::isError($mail)) { 
    echo("<p>" . $mail->getMessage() . "</p>"); 
} else { 
    echo("<p>Message successfully sent!</p>"); 
} 

你可以找到一個例子here

6

PHPMailer處理錯誤很好,也是一個不錯的腳本用於通過SMTP發送郵件...

if(!$mail->Send()) { 
    echo "Mailer Error: " . $mail->ErrorInfo; 
} else { 
    echo "Message sent!"; 
} 
+0

其實我認爲它會迴應一個錯誤,如果你沒有設置異常屬性爲真 – AntonioCS 2010-02-24 11:20:56

+0

我潛入其代碼,它只是使用臨時的'安全模式'+ @mail()來處理錯誤。 – 2017-07-19 07:43:29

4

也使用http://php.net/error_get_last不會幫助你,因爲郵件()不emmit其誤差爲這功能。

唯一的辦法似乎是使用正確的郵件,就像上面已經提到的那樣。

+2

這個聲明似乎有一些價值,'mail'對我來說返回false,但'error_get_last'爲空。 – yoshi 2014-06-19 11:23:39