gpt4 book ai didi

php - Swift 邮件未捕获无效电子邮件的异常

转载 作者:行者123 更新时间:2023-12-01 13:51:39 24 4
gpt4 key购买 nike

我正在使用 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 [ex@example@ex.com] does not comply with RFC 2822, 3.6.2.
thrown in /swiftmailer/classes/Swift/Mime/Headers/MailboxHeader.php on line 352

谁能帮忙解决一下?简单地说,它应该捕获异常,这样其他功能就不会受到影响。

最佳答案

您将 try ... catch-block 包裹在您编写 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 对象时使用它,如下所示:

$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";
}

此外,我还建议围绕 $result = $mailer->send($message); 进行一些 try-catch,因为如果其他地方出错,它可能会抛出异常。

关于php - Swift 邮件未捕获无效电子邮件的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31137017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com