使PHP的mail()异步 [英] Making PHP's mail() asynchronous

查看:180
本文介绍了使PHP的mail()异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有PHP的 mail()使用 ssmtp ,它不没有队列/线轴,与AWS SES同步。

I have PHP's mail() using ssmtp which doesn't have a queue/spool, and is synchronous with AWS SES.

我听说可以使用 SwiftMail 提供了一个线轴,但是我无法使用简单的配方来使用它,就像我目前使用 mail()一样。

I heard I could use SwiftMail to provide a spool, but I couldn't work out a simple recipe to use it like I do currently with mail().

我希望最少的代码提供异步邮件。我不在乎电子邮件是否发送失败,但是有一个日志是很好的。

I want the least amount of code to provide asynchronous mail. I don't care if the email fails to send, but it would be nice to have a log.

任何简单的提示或技巧?缺少运行完整的邮件服务器?我正在想一个 sendmail 包装器可能是答案,但我无法解决 nohup

Any simple tips or tricks? Short of running a full blown mail server? I was thinking a sendmail wrapper might be the answer but I couldn't work out nohup.

推荐答案

php-fpm



您必须运行php-fpm fastcgi_finish_request 可供使用。

echo "I get output instantly";
fastcgi_finish_request(); // Close and flush the connection.
sleep(10); // For illustrative purposes. Delete me.
mail("test@example.org", "lol", "Hi");

在完成向用户的请求后,排队任意任意代码进行处理非常简单:

It's pretty easy queuing up any arbitrary code to processed after finishing the request to the user:

$post_processing = [];
/* your code */
$email = "test@example.org";
$subject = "lol";
$message = "Hi";

$post_processing[] = function() use ($email, $subject, $message) {
  mail($email, $subject, $message);
};

echo "Stuff is going to happen.";

/* end */

fastcgi_finish_request();

foreach($post_processing as $function) {
  $function();
}



Hipster background worker



立即超时卷曲,让新的请求处理。我在共享的主机之前这样做是很酷的。

Hipster background worker

Instantly time-out a curl and let the new request deal with it. I was doing this on shared hosts before it was cool. (it's never cool)

if(!empty($_POST)) {
  sleep(10);
  mail($_POST['email'], $_POST['subject'], $_POST['message']);
  exit(); // Stop so we don't self DDOS.
}

$ch = curl_init("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
  'email' => 'noreply@example.org',
  'subject' => 'foo',
  'message' => 'bar'
]);

curl_exec($ch);
curl_close($ch);

echo "Expect an email in 10 seconds.";

这篇关于使PHP的mail()异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆