总结:
- 要做的主要更改:重用您的邮件连接,最好是创建消息,所以它只在需要时完成,通常只做一次
- 检查您如何实例化 SwiftMailer 并确认它是最佳方式
- 您的 SwiftMailer 类版本似乎有点旧 (4.0.5),您可以查看更新的版本
更详细:
重用实例化对象。您每次都在重新创建邮件传输,从而导致开销。你不应该那样做。如果支持,您可以将 batchSend() 用于大量电子邮件。请参阅this question 中的使用示例。一个应用例子:
$message = Swift_Message::newInstance(...)
->setSubject('A subject')
->setFrom(array('myfrom@domain.com' => 'From Me'))
->setBody('Your message')
;
while(list($targetadd, $targetname) = each($targetlist))
{
$message->addTo($targetadd, $targetname);
}
$message->batchSend();
请注意,虽然 batchSend() 是 removed in 4.1.0 RC1 of SwiftMailer。据我所知,它是internally called send() in a loop,所以你应该能够通过多次调用 send() 来获得相同的效果,但至少要重用你的邮件传输,这样你就不会每次都重新实例化它(如果适用,也创建消息)。
从official documentation 的批量发送示例中,您可以使用 send() 来批量发送电子邮件
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john@doe.com' => 'John Doe'))
->setBody('Here is the message itself')
;
// Send the message
$failedRecipients = array();
$numSent = 0;
$to = array('receiver@domain.org', 'other@domain.org' => 'A name');
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo(array($address => $name));
}
$numSent += $mailer->send($message, $failedRecipients);
}
传输协议。 另外要注意的是 SwiftMailer 是一个包装类。它在引擎盖下实际使用的是您定义的内容。在您的情况下,您使用的是 SMTP 传输,它比邮件传输(mail() 函数)更好,但可能不是最优化的。
你没有说你是否明确想要使用它以及你有哪个环境,但是在 linux 环境中,你可以直接调用 sendmail 类似的东西
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
这可以提供更好的性能。 SwiftMailer usage documentation 有更多关于不同传输的信息。
类版本。根据您的评论,您使用的是 4.0.5 版本。当前版本是4.1.8.,自从批量发送以来,有些东西已经改变了,所以你可能也想看看。
编辑:关于 batchSend()、当前版本和手动链接的更新信息。