PHPMailer using Gmail SMTP slow when sending emails
php, phpmailer, windows
Solution
The slowness (or failure due to timeouts) is because Google supports IPv6 addressing but your network does not. (e.g. Digital Ocean does not yet support IPv6 for SMTP traffic). So, use this:
$mail->Host = gethostbyname("smtp.gmail.com");
gethostbyname() will return the IPv4 address.
For me, my PHPMailer script went from ~2 minutes execution time to <4 seconds
Problem
I found few older threads that have a similar issue but most of them didn't have answers or if they had, the suggestions weren't relevant in my case. I had a complete setup at one point with PHP mail function and it worked great. I had to format my hard drive at one point and setup the server from scratch. Afterwards, PHP mail function became slow. While researching solutions for that, I found that most people recommended PHPMailer. I switched to that but the problem still persisted. Most of the time, I am sending at least two emails per page with different bodies but using the same object. There is about 3-4 second delay. Please find the relevant code below ($email1 and $email2 are arrays containing valid email addresses): ``` function sendEmail ($email1, $subject1, $message1, $email2, $subject2, $message2) { require_once('../PHPMailer/class.phpmailer.php'); $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPDebug = 0; $mail->SMTPAuth = true; $mail->SMTPSecure = 'ssl'; $mail->Host = "smtp.gmail.com"; $mail->Port = 465; $mail->IsHTML(true); $mail->Username = $gmail_username; $mail->Password = $gmail_password; $mail->SetFrom($gmail_address,$email_title); $mail->Subject = $subject1; $mail->Body = $message1; foreach($email1 as $k => $v) { $mail->AddAddress($v); } if(!$mail->Send()) { $emailreturn['cust'] = 0; } else { $emailreturn['cust'] = 1; } $mail->ClearAddresses(); $mail->Subject = $subject2; $mail->Body = $message2; foreach($email2 as $k => $v) { $mail->AddAddress($v); } if(!$mail->Send()) { $emailreturn['partner'] = 0; } else { $emailreturn['partner'] = 1; } $mail->ClearAddresses(); } ``` I don't see any error through debug and messages, it just takes longer than usual to send the email. What I've tried: - I turned off the Firewall just to test it, and it's the same. - Switched to 'tls', that made it even slower - Sent each email using an object, that gave a 3-4 second delay for each email - Played around with optional configuration, comment out or set false, all with the same result Is there anything else missing in the mailer setup or is there some behind-the-scenes configuration that I should check? Thanks