我在我的hostgator服務器上設置了一個cron作業,返回值1(發送電子郵件),但實際上並未發送電子郵件。當我在瀏覽器中手動調用php文件時,會發送電子郵件。它不通過cron運行。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'] = "[email protected]";
$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 = "[email protected]";
$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,但未發送電子郵件。
任何建議將不勝感激!
檢查郵件日誌文件?如果從命令行運行腳本,會發生什麼情況? – nogad
當我從瀏覽器運行它時,郵件被髮送。從PuTTY shell或cron作業運行時,不會發送電子郵件。 – rottlover
SOLUTION: 事實證明,郵件被SMTP服務器的垃圾郵件過濾器阻塞。用hostgator技術支持2.5小時後,看起來我們已經解決了問題。我很高興這不是一個編碼問題。 ;) – rottlover