doumeng1143 2014-06-21 02:18
浏览 61

使用phpmailer的后备smtp服务器

I'm using gmail as my smtp server with phpmailer().

$mail->Host= "ssl://smtp.gmail.com"

How do i specify a separate smtp server just as a back up incase the connection to gmail fails ?

  • 写回答

2条回答 默认 最新

  • dsv73806 2014-06-21 04:12
    关注

    Check out this tutorial: http://www.web-development-blog.com/archives/send-e-mail-messages-via-smtp-with-phpmailer-and-gmail/

    And go to the section: Advanced setup with fall-back SMTP server

    First add the variables for the backup email service, something like:

    define('SMTPUSER', 'you@yoursmtp.com'); // sec. smtp username
    define('SMTPPWD', 'password'); // sec. password
    define('SMTPSERVER', 'smtp.yoursmtp.com'); // sec. smtp server
    

    Then we modify the mail send function to incorporate our backup plan.

    function smtpmailer($to, $from, $from_name, $subject, $body, $is_gmail = true) { 
        global $error;
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; 
        if ($is_gmail) {
            $mail->SMTPSecure = 'ssl'; 
            $mail->Host = 'smtp.gmail.com';
            $mail->Port = 465;  
            $mail->Username = GUSER;  
            $mail->Password = GPWD;   
        } else {
            $mail->Host = SMTPSERVER;
            $mail->Username = SMTPUSER;  
            $mail->Password = SMTPPWD;
        }        
        $mail->SetFrom($from, $from_name);
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AddAddress($to);
        if(!$mail->Send()) {
            $error = 'Mail error: '.$mail->ErrorInfo;
            return false;
        } else {
            $error = 'Message sent!';
            return true;
        }
    }
    

    And finally use our new function, using our backup (by passing $is_gmail = false) only if necessary.

    $msg = 'Hello World';
    $subj = 'test mail message';
    $to = 'to@mail.com';
    $from = 'from@mail.com';
    $name = 'yourName';
    
    if (smtpmailer($to, $from, $name, $subj, $msg)) {
        echo 'Yippie, message send via Gmail';
    } else {
        if (!smtpmailer($to, $from, $name, $subj, $msg, false)) {
            if (!empty($error)) echo $error;
        } else {
            echo 'Yep, the message is send (after doing some hard work)';
        }
    }
    

    Example code was taken from the tutorial linked above.

    评论

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab