PHPMailer过早发送电子邮件

时间:2013-08-26 18:10:35

标签: php phpmailer

我有以下代码,我需要帮助。我从PHPMailer示例中得到了这个片段:

//Send the message, check for errors
if(!$mail->Send()) {

    die ("Mailer Error: " . $mail->ErrorInfo);

} else {

    echo "Message sent!";

}

如果if为真,则似乎在if语句的实际第一行发送电子邮件。这是对的吗?

如果这是正确的,我如何检查一切是否正常,如所有电子邮件详细信息都有效,运行else,这将执行一些数据库输入,然后发送电子邮件。< / p>

这可能吗?


更新

以下似乎有效:

if($mail->ErrorInfo) {

    echo "some error happened";

} else {

    echo "email details are ok<br />";
    echo "do database entry stuff<br />";
    echo "if new record exists, send email";
// if (db entry was successful) {
        $mail->Send();
// } else {
    echo "email not sent, something wrong at db entry stage";
// }

}

任何人都可以看到使用此方法的任何问题吗?

3 个答案:

答案 0 :(得分:1)

如果您的邮件依赖于数据库条目成功,那么在尝试邮件之前应首先检查它们,就像数据库调用不成功一样,根本不需要做任何邮件

if( !$dbStuffSuccessful ) {
   //Handle db failure and leave
   die("db error");
} 
//We can assume that db entries were successfull 
//lets do the mail stuff

//Check mail stuff is valid, mailer does not have "checks" 
//like ->isValidEmail()
//so you will have to do these checks yourself
...

//Do whatever mailer stuff
$mailer->AddAddress($blah,$blah);
...

//Now try to send, send it seems is the only one that 
//triggers any errors so attempt and see if there is 
//an error
if(!$mail->send()) {
   //Whatever error happened will be in ->ErrorInfo 
   //Rollback db stuff and leave
   $db->dorollback();
   die('mail unsuccessful, db rolledback, mail error: '.
        print_r($mail->ErrorInfo,true));
}

//Ok we can assume no errors in db and no errors with mailer
//finish whatever else we need to do

答案 1 :(得分:0)

如果邮件无法发送,$ mail-&gt; send()行将返回false - 上述内容应该可以正常运行。

答案 2 :(得分:0)

如果您想在电子邮件之前进行数据库编辑,然后将数据库代码放在您显示的代码之前,那么您显示的代码将起作用。如果电子邮件不起作用,则可以在die语句之前使用代码回滚数据库更改。

我就是这样做的。

//Update database here

if(!$mail->Send()) {
    //email failed, rollback database changes.
    die ("Mailer Error: " . $mail->ErrorInfo);

} else {
    //everything's fine.
    echo "Message sent!";

}

如果是SQL,您甚至可以使用transactionrollback功能