代码之家  ›  专栏  ›  技术社区  ›  oshirowanen

PHPMailer过早发送电子邮件

  •  1
  • oshirowanen  · 技术社区  · 12 年前

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

    //Send the message, check for errors
    if(!$mail->Send()) {
    
        die ("Mailer Error: " . $mail->ErrorInfo);
    
    } else {
    
        echo "Message sent!";
    
    }
    

    如果 if 是的,似乎是在 如果 陈述这是正确的吗?

    如果这是正确的,我如何检查一切是否正常,如中所示,所有电子邮件详细信息都有效,运行 else ,它会做一些数据库输入的事情,然后发送电子邮件。

    这可能吗?


    更新:

    以下内容似乎有效:

    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 回复  |  直到 12 年前
        1
  •  1
  •   Patrick Evans    12 年前

    如果您的邮件取决于数据库条目是否成功,那么在尝试发送邮件之前应该先检查它们,就好像数据库调用不成功一样,根本不需要做任何邮件工作

    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
    
        2
  •  0
  •   Ashley    12 年前

    如果邮件无法发送,则$mail->send()行将返回false-上面的操作应该可以很好地工作。

        3
  •  0
  •   Lex - Boycott Slack - see bio    12 年前

    如果你想在电子邮件之前编辑数据库,那么你显示的代码会起作用,然后把数据库代码放在显示的代码之前。如果电子邮件不起作用,您可以在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,您甚至可以使用 transaction rollback 特征

    推荐文章