如何在电子邮件上设置时间延迟 php Mail().



这是我的PHP脚本,是否可以在邮件发送之前添加几秒钟的时间延迟?例如,每次我使用联系表格时,我都希望在延迟 20 秒后发送邮件。

    <?php
// Debugging tools. Only turn these on in your development environment.
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
// Special mail settings that can make mail less likely to be considered spam
// and offers logging in case of technical difficulties.
ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);
//variables
$name = strip_tags(htmlspecialchars($_POST['Name']));
$email_address = strip_tags(htmlspecialchars($_POST['Email']));
$message = strip_tags(htmlspecialchars($_POST['Message']));
// Create the email and send the message
$to = ''; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from example... contact form.nn"."Here are the details:nnName: $namennEmail: $email_addressnnMessage:n$message";
$headers = "From: noreply@example.xyz n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";  
if(mail($to,$email_subject,$email_body,$headers)){ echo "Mail sent!";} else{ echo "Error, check your logs."; }
return true; 

mail函数在PHP中阻塞。您不能在脚本中设置相同内容。更好的实现是在该队列上有一个 redis 队列和推送邮件请求。完成此操作后,您可以拥有一个工作节点,该节点解析 redis 队列中的数据并在后台使用 mail 函数。这样,脚本本质上就变得非阻塞。

redis还有其他替代品,如rabbitmq和zmq。

最新更新