如何在后台使用 PHPMailer 发送电子邮件?
PHPMailers 在从 gmail 帐户发送电子邮件方面做得很好.但这需要相当长的时间,并且在发送电子邮件之前页面不会显示响应.有什么方法可以在后台发送电子邮件,以便为用户提供更好的用户体验?谢谢!
PHPMailers is doing a fine job in sending emails from a gmail account. But it takes quite a bit of time, and the page won't show the response until the email has been sent. Any ways to send the email in the background so that I can provide a better user experience to the user? Thanks!
推荐答案
使用 email queue 和 php exec() 是最好的方法之一.
它会在需要时触发(避免使用 CRON),它很快,因为它被称为后台,并且是即时的.
The use of an email queue and php exec() is one of the best ways.
It will trigger when needed (avoiding the use of CRONs), it's fast because it is called backgrounded, and immediate.
1.电子邮件队列.使用插入获取表的 MySQL 中的所有字段,例如:
1. Email queue. Take all fields in a table's MySQL with an insert, something like:
$queryIN="INSERT INTO email_queue (date,subject,body,destination,idle) values (...)";
mysql_query($queryIN);
这很重要,因为您需要一个独立的后台进程,因此注册和审核所有外发电子邮件也是一个好主意.
That's important because you will need an independent background process, so also it's a good idea for registering and auditing all outgoing emails.
<强>2.PHP exec(). 在 MySQL 中插入之后是调用外部执行的时候了:
2. PHP exec(). After inserting in MySQL is time to call as external execution:
exec("wget -qO- http://example.com/index.php?process_email_queue=1 &> /dev/null &");
- 注意,来自 wget
-q0-
和&> 的选项.../dev/null &
需要抑制输出并作为后台进程调用. - Take note, options from wget
-q0-
and&> ... /dev/null &
are needed to suppress output and call as a background process.
3.用于处理队列调用的相同脚本文件 index.php 或其他:
这样,它会调用我们的index.php(你可以使用其他名称文件),并处理传出:
This way, it will call our index.php (you can use other name file), and process outgoing:
if ($_GET['process_email_queue']==1) { ...code for sending idle emails queue... }
也许您必须为 exec()
触摸一些 php.ini 选项,这没什么大不了的.
Perhaps you have to touch some php.ini options for exec()
, is not a big deal.
一旦一切正常运行,您将提供更好的网络导航和电子邮件处理,以实现快速响应和零等待.
Once everything is running correctly, you will offer a better web navigation and email handling for fast response and zero waits.
在某些情况下,您将从直接电子邮件等待 2.60 秒到 queue-exec-background 0.024 秒,速度提高了 11 倍.
相关文章