我有以下鳕鱼基本上发送一条消息,其中包含来自MySQL的一些用户数据。现在的问题是,有时会发送有问题的电子邮件,但如果我需要重新发送,则不会发送。这是代码:
<?php
//including the database connection file
include("config.php");
//getting id of the data from url
$id = $_GET['id'];
//fetching data in descending order (lastest entry first)
$result = mysql_query("SELECT * FROM my_table_name Where id='$id'");
if($res = mysql_fetch_array($result)) {
$name = $res['name'];
$email = $res['email'];
$date = $res['date'];
if(empty($id)) {
echo "<font color='red'>Error: Did not send.</font><br/>";
} else {
// The message
$message = "Hi $name,\r\n\r\nThis email is to inform you that your
\r\n\r\nRegards, \r\n Me.";
$headers = 'From: no-reply@mydomain.org' . "\r\n" .
'Reply-To: no-reply@mydomain.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$Subject = 'Hello';
// Send
mail($email, $Subject, $message, $headers);
//display success message
echo "<font color='green'>Email sent successfully to $name.</font><br/>";
echo "<br/><a href='index.php' class='button button1 link'>Go Back to Overview</a>";
}
}
?>
非常感谢任何帮助。
答案 0 :(得分:0)
如果我正确地理解了您的问题,那么有时候mail
函数调用会失败:
您可以在邮件呼叫中添加重试逻辑:
$triesLeft = 5;
while ($triesLeft > 0) {
$rc = mail(...);
if ($rc === true) {
break;
}
sleep(1); // Space to improve here - see exponential backoff, for instance
$triesLeft -= 1;
}
if ($triesLeft === 0) {
// Log critical error
}
但这可能并且会在您的响应时间中引入延迟,在某些情况下,客户端甚至会超时。
所以通常这个问题的解决方案不是立即发送电子邮件,而是快速将其放入任何类型的队列(即使是简单的db表就足够了),然后创建另一个将发送所有内容的工作脚本未发送的。
您可以将此重试逻辑移动到此工作程序脚本并随意休眠,它不会阻止客户端。
此解决方案的唯一“缺点”是:
mail
电话的结果(无论如何这都是无用的,因为这意味着只有“接受交付”,而不是实际交付),并且解决方案的大纲可能是:
form.php (gets called when customer submits form):
get request parameters
form email subject, body from request parameters
save email to db with status = unsent
worker.php (should be always running in an infinite loop or something like that in background on server):
get unsent email from db
try to send it, retrying if needed
if sent successfully - mark email as sent
if failed to send - mark email an failed, log critical error, mitigate manually