2015-06-30 62 views
2

我使用Swift郵件程序發送電子郵件,它無法捕獲無效電子郵件地址的例外&會引發錯誤。Swift郵件無法捕獲無效電子郵件的例外

我的代碼是:

try 
{ 
    $message->setBody($html, "text/html"); 
    $result = $mailer->send($message); 
} 
catch(Swift_RfcComplianceException $e) 
{ 
    echo "Address ".$email." seems invalid"; 
} 

對於不符合RFC它只是拋出這個錯誤的電子郵件地址:

Fatal error: Uncaught exception Swift_RfcComplianceException with message Address 
in mailbox given [[email protected]@ex.com] does not comply with RFC 2822, 3.6.2. 
thrown in /swiftmailer/classes/Swift/Mime/Headers/MailboxHeader.php on line 352 

任何人可以幫助解決嗎?簡單地說,它應該捕獲一個異常,以便其他函數不受影響。

回答

2

你正在包裝try ... catch-圍繞swiftmailer郵件組成的錯誤部分。

the manual

摘錄:

If you add recipients automatically based on a data source that may contain invalid email addresses, you can prevent possible exceptions by validating the addresses using Swift_Validate::email($email) and only adding addresses that validate. Another way would be to wrap your setTo() , setCc() and setBcc() calls in a try-catch block and handle the Swift_RfcComplianceException in the catch block.

因此,你應該使用它,而將地址添加到您的Swift_Message -object,像這樣:此外

$message = Swift_Message::newInstance(); 

// add some message composing here... 

$email = "somewrongadress.org"; 
try { 
    $message->setTo(array($email)); 
} catch(Swift_RfcComplianceException $e) { 
    echo "Address ".$email." seems invalid"; 
} 

,我周圍的一些建議的try-catch $result = $mailer->send($message);也是如此,因爲如果出現其他錯誤,它可能會拋出異常。

+0

明白了,工作得很好:) –

相關問題