Fallback smtp servers with phpmailer

2019-08-12 17:56发布

问题:

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 ?

回答1:

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.



回答2:

No need for all that hard work, it's built in to PHPMailer. When you set the host, just add more than one in a semicolon-delimited list (you can also specify security settings at the same time), like this:

$mail->Host = 'tls://smtp.gmail.com:587;tls://smtp2.gmail.com;ssl://mail.example.net:465';

PHPMailer will try them all, in the provided order, before giving up. Make sure you are using a fairly recent version of PHPMailer as there were bugs in this area in older versions.