通过 PhpMailer 异步发送电子邮件

Send email Asynchronously via PhpMailer

我正在使用 PHPMailer 发送电子邮件,效果很好。但问题是,由于它是同步发送电子邮件,因此后续页面加载需要很长时间。

我正在使用本示例中所示的 PhpMailer https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps

我想知道是否有办法使电子邮件传送异步。我对此进行了研究,发现 sendmail 有一个选项可以将 DeliveryMode 设置为 "background mode" - source http://php.net/manual/en/function.mail.php

mail($to, $subject, $message, $headers, 'O DeliveryMode=b');

我想知道在 PhpMailer 中是否可以做类似的事情?有人成功过吗?

编辑:-(附加信息) PhpMailer 似乎可以配置为使用 sendmail - https://github.com/PHPMailer/PHPMailer/blob/master/class.phpmailer.php 因此我想知道是否可以以某种方式利用它来启用后台交付。

/**
 * Which method to use to send mail.
 * Options: "mail", "sendmail", or "smtp".
 * @type string
 */
public $Mailer = 'mail';

/**
 * The path to the sendmail program.
 * @type string
 */
public $Sendmail = '/usr/sbin/sendmail';
/**
 * Whether mail() uses a fully sendmail-compatible MTA.
 * One which supports sendmail's "-oi -f" options.
 * @type boolean
 */
public $UseSendmailOptions = true;

/**
 * Send messages using $Sendmail.
 * @return void
 */
public function isSendmail()
{
    $ini_sendmail_path = ini_get('sendmail_path');
    if (!stristr($ini_sendmail_path, 'sendmail')) {
        $this->Sendmail = '/usr/sbin/sendmail';
    } else {
        $this->Sendmail = $ini_sendmail_path;
    }
    $this->Mailer = 'sendmail';
}

此外 - 显然可以通过 php.ini 设置 sendmail 选项 http://blog.oneiroi.co.uk/linux/php/php-mail-making-it-not-suck-using-sendmail/

我更愿意将此作为 api 调用与 php.ini 的内联参数,因此这不是全局更改。有人试过吗?

根据this phpMailer doesn't support this type of call. You would have to write your own threaded class in order to do make an async call. See pThreads and the Thread class. One other solution was found here

错误的方法。

PHPMailer 不是您要求的邮件服务器。 SMTP 是一种冗长、冗长的协议,容易出现延迟和吞吐量降低,并且绝对不适合在典型的网页提交期间以交互方式发送(这就是 BlackHatSamurai 链接到的问题可能正在做的事情)。许多人正是这样做而侥幸逃脱,但不要误以为这是一个好的解决方案,绝对不要尝试自己实施 MTA。

您链接到的 gmail 示例使用 SMTP 连接到远程服务器,这总是比在本地提交慢。如果您通过 sendmail(或 mail() - 它基本上是同一件事)提交到本地服务器并且花费了超过 0.1 秒,那么您做错了。即使是发送到本地主机的 SMTP 也不会花费太多时间,发送到附近的智能主机也不会太慢。

尝试使用线程作为后台事物是一大堆蠕虫病毒,这完全不是解决这个问题的方法 - 与适当的邮件服务器相比,无论你以这种方式实现什么都会很糟糕。只是不要这样做。

正确的做法是安装一个本地邮件服务器,然后用 PHPMailer 将邮件提交给它。这种方式非常快(每秒数百条消息),并且您必须精确地执行 nothing 才能使其工作,因为这是默认情况下 PHPMailer 的工作方式。

然后邮件服务器将执行它应该执行的操作 - 对您的邮件进行排队、处理连接问题、传递延迟、退回以及您没有考虑的所有其他事情。