使 PHP 的 mail() 异步 [英] Making PHP's mail() asynchronous
问题描述
我有 PHP 的 mail()
使用 ssmtp 没有队列/spool,并与 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
您必须为 fastcgi_finish_request 运行 php-fpm可用.
php-fpm
You must run php-fpm for fastcgi_finish_request to be available.
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();
}
时髦的后台工作者
立即超时 curl 并让新请求处理它.在它很酷之前,我是在共享主机上这样做的.(从来都不酷)
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屋!