我尝试了几种方法,但没有一种方法,包括StackOverFlow -> Swiftmailer TransportException get uncaught by try catch block中的一种方式。
我需要捕获可以在我的类中运行Swiftmailer类的实例来发送电子邮件的块中生成的异常
/**
* @throws Be msut catch swiftmailer exception Swift_TransportException because ->setTo($send_to) containt '' (not valid email sender)
* But not catch my code.
*/
$transport = \Swift_SmtpTransport::newInstance()
->setHost($settings['smtp_host'])
->setPort($settings['smtp_port'])
->setEncryption($settings['smtp_security'])
->setUsername($settings['smtp_user'])
->setPassword($settings['smtp_pass']);
$mailer = \Swift_Mailer::newInstance($transport);
echo "Verify code\n";
try {
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom(array($settings['smtp_mail_sender'] => $settings['smtp_name_sender']))
->setTo($send_to)
->setBody($msg);
$result = $mailer->send($message);
} catch (\Swift_TransportException $Ste) {
echo "EROORRRRRRRRRRRRRRRRRRRR\n\n\n";
}
在控制台上运行时显示错误
php -q cprsyncbackup.php -option param
No llegue
PHP Fatal error: Uncaught exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [] does not comply with RFC 2822, 3.6.2.' in /Volumes/iDatos/abkrim/ownCloudTDC/tamainut/desarrollo/cprsync/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php:348
Stack trace:
#0 /Volumes/iDatos/abkrim/ownCloudTDC/tamainut/desarrollo/cprsync/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php(263): Swift_Mime_Headers_MailboxHeader->_assertValidAddress('')
#1 /Volumes/iDatos/abkrim/ownCloudTDC/tamainut/desarrollo/cprsync/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php(106): Swift_Mime_Headers_MailboxHeader->normalizeMailboxes(Array)
#2 /Volumes/iDatos/abkrim/ownCloudTDC/tamainut/desarrollo/cprsync/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php(63): Swift_Mime_Headers_MailboxHeader->setNameAddresses(Array)
#3 /Volumes/iDatos/abkrim/ownCloudTDC/tamainut/desarrollo/cprsync/vendor/swiftmailer/swiftmailer/li in /Volumes/iDatos/abkrim/ownCloudTDC/tamainut/desarrollo/cprsync/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php on line 348
答案 0 :(得分:4)
你正在围绕swiftmailer邮件组成的错误部分包裹try ... catch
-
摘自the manual:
如果您根据可能的数据源自动添加收件人 包含无效的电子邮件地址,可以防止可能的异常 通过使用
Swift_Validate::email($email)
和。验证地址 仅添加验证的地址。另一种方法是包装你的setTo()
,setCc()
和setBcc()
调用try-catch块和句柄 阻止块中的Swift_RfcComplianceException
。
因此,您应该在向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";
}
/* and now your transport... */
try {
$result = $mailer->send($message);
} catch (\Swift_TransportException $Ste) {
echo "EROORRRRRRRRRRRRRRRRRRRR\n\n\n";
}
That should do the job.