【发布时间】:2017-04-27 06:30:48
【问题描述】:
我在我的 hostgator 服务器上设置了一个 cron 作业,它返回值 1(已发送电子邮件),但实际上并没有发送电子邮件。当我在浏览器中手动调用 php 文件时,会发送电子邮件。如果通过 cron 运行则不会。
本月早些时候,我将我的网站从 hostgator 上的一台服务器移动到另一台服务器(在 hostgator 上),以便获得 SSL 和专用 IP 地址。自从移动站点以来,cron 作业工作正常除了发送电子邮件的部分(即,数据库功能工作正常)。我已经联系了 hostgator 技术支持,但他认为问题出在我的代码中。
考虑到我的服务器信息可能不正确,我转而使用 smtp.gmail.com 并使用 gmail 帐户发送邮件,但这也不起作用。请帮忙!
cron 作业是这样设置的:
* 7 * * * /opt/php56/bin/php /home/user/public_html/somefolder/sendmailcron.php
(在测试时,我将其更改为每 2 分钟运行一次:*/2 * * * *)
这里是 sendmailcron.php 脚本:
<?php
$now = date("Y-m-d H:i:s");
$msgcontent = [];
$msgcontent['email'] = "recipient@example.com";
$msgcontent['name'] = "Recipient Name";
$msgcontent['textpart'] = "This is the text version of the email body.";
$msgcontent['htmlpart'] = "<p>This is the <strong>HTML</strong> version of the email body.</p>";
$msgcontent['subject'] = "Test email sent at " . $now;
$result = sendMyMail($msgcontent, "HTML");
exit();
function sendMyMail($msgcontent, $format="HTML") {
require_once '/home/user/public_html/somefolder/swiftmailer/lib/swift_required.php';
$result = 0;
$subject = $msgcontent['subject'];
$email = $msgcontent['email'];
if (strlen($email) == 0) {
return 0;
}
$name = $msgcontent['name'];
$emailbody = $msgcontent['textpart'];
$emailpart = $msgcontent['htmlpart'];
switch($format) {
case "TEXT":
$msgformat = 'text/plain';
break;
case "HTML":
$msgformat = 'text/html; charset=UTF-8';
break;
default:
$msgformat = 'text/html';
break;
}
$adminemailaddress = "me@mydomain.com";
$adminemailpwd = 'myadminpwd';
$sendername = 'My Real Name';
$transport = Swift_SmtpTransport::newInstance('mygator1234.hostgator.com', 465, "ssl")
->setUsername($adminemailaddress)
->setPassword($adminemailpwd)
;
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
if($format == "TEXT") {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailbody)
->setContentType($msgformat)
;
}
else {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailpart)
->setContentType($msgformat)
;
}
//This is where we send the email
try {
$result = $mailer->send($message); //returns the number of messages sent
} catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
return $result; //will be 1 if success or 0 if fail
}
?>
返回值始终为 1,但不发送电子邮件。
任何建议将不胜感激!
【问题讨论】:
-
检查了邮件日志文件?如果从命令行运行脚本会发生什么?
-
当我从浏览器运行它时,会发送邮件。从 PuTTY shell 或 cron 作业运行时,不会发送电子邮件。
-
解决方案:事实证明,电子邮件被 SMTP 服务器的垃圾邮件过滤器拦截。在使用 hostgator 技术支持 2.5 小时后,看来我们已经解决了问题。我很高兴这不是编码问题。 ;)
标签: php email cron swiftmailer