我可以从 ->setTo(array(. 使用以下代码找到 swiftmailer 中被拒绝的地址:
$mailer = Swift_Mailer::newInstance( ... );
$message = Swift_Message::newInstance( ... )
->setFrom( ... )
->setTo(array(
'receiver@bad-domain.org' => 'Receiver Name',
'other@domain.org' => 'A name',
'other-receiver@bad-domain.org' => 'Other Name'
))
->setBody( ... )
;
// Pass a variable name to the send() method
if (!$mailer->send($message, $failures))
{
echo "Failures:";
print_r($failures);
}
/*
Failures:
Array (
0 => receiver@bad-domain.org,
1 => other-receiver@bad-domain.org
)
*/
现在我也想从 Cc 和 Bcc 字段中找出被拒绝的地址。如何添加类似的代码?是否有教程或解决方法? swiftmailer 教程中没有示例。
最佳答案
您可以使用 try-catch
block 来设置收件人、抄送和密件抄送电子邮件地址。
来自 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 yoursetTo()
,setCc()
andsetBcc()
calls in a try-catch block and handle theSwift_RfcComplianceException
in the catch block.
因此您可以在 $message
对象上使用 try-catch
:
$message = Swift_Message::newInstance();
$emails = array(
'receiver@bad-domain.org' => 'Receiver Name',
'other@domain.org' => 'A name',
'other-receiver@bad-domain.org' => 'Other Name'
);
// loop through emails and set the individually to catch exceptions
foreach($emails as $email => $name)
{
try {
$message->setTo(array($email => $name));
} catch(Swift_RfcComplianceException $e) {
echo "The email ".$email." seems invalid";
}
}
// And do the same thing with cc and bcc emails
$ccEmails = array(
'receiver@ccemail.org' => 'CC Receiver Name'
);
foreach($ccEmails as $email => $name)
{
try {
$message->setCc(array($email => $name));
} catch(Swift_RfcComplianceException $e) {
echo "The email ".$email." seems invalid";
}
}
如果您希望如何处理失败,您可以将失败设置为变量。
编辑:如果您有一系列用户的名字和姓氏不同,您可以使用以下内容:
$users = array(
array('email' => 'receiver@bad-domain.org', 'first' => 'Receiver', 'last' => 'Name'),
array('email' => 'other@domain.org', 'first' => 'A', 'last' => 'name'),
array('email' => 'other-receiver@bad-domain.org', 'first' => 'Other', 'last' => 'Name')
);
// loop through users and set the individually to catch exceptions
foreach($users as $user)
{
try {
$message->setTo(array($user['email'] => $user['first'].' '.$user['last']));
} catch(Swift_RfcComplianceException $e) {
echo "The email ".$user['email']." seems invalid";
}
}
关于php - 找出 Cc 和 Bcc 中被拒绝的地址 - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34218299/