Search code examples
phpsmtpphpmailer

PHP - PHPMailer send email with multiple SMTP hosts


I am working with PHPMailer to send emails with SMTP servers. I am successfully able to send email. But, I want configure the code with multiple SMTP servers with different usernames and passwords. How to achieve this functionality. As per PHPMailer documentation, we can provide backup SMTP server. But how to configure it with different username and passwords.

Below is the code snippet,

$mail->SMTPDebug = 2;                                       // Enable verbose debug output
$mail->isSMTP();                                            // Set mailer to use SMTP
$mail->Host       = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
$mail->Username   = '[email protected]';                     // SMTP username
$mail->Password   = 'secret';                               // SMTP password
$mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
$mail->Port       = 587;                                    // TCP port to connect to

Please help me with this. Any help will be appreciated. Thanks.


Solution

  • First of all define your servers, then pick the one you want to use, for example:

    $servers = [
        [
            'host'     => 'server1.example.com',
            'username' => 'user 1',
            'password' => 'password1',
        ],
        [
            'host'     => 'server2.example.com',
            'username' => 'user 2',
            'password' => 'password2',
        ],
        [
            'host'     => 'server3.example.com',
            'username' => 'user 3',
            'password' => 'password3',
        ],
    ];
    
    //Pick a random server (or however you want to select a server)
    $server = $servers[array_rand($servers)];
    
    //Use the selected server values for mailing
    $mail->Host = $server['host'];
    $mail->Username = $server['username'];
    $mail->Password = $server['password'];