简体   繁体   中英

sending phpmailer smtp email with gmail takes long time (1.5 seconds)

The following script takes about 1.5 seconds to send an email as measured by the timers across the $mail->send() line. If I don't use smtp, it goes MUCH faster, however, some mail servers will block the incoming email.

What is causing the delay? If there is nothing that could be done about it, what would be a good solution to prevent the user from having to wait for it?

<?php
require_once ('../../application/classes_3rd/PHPMailer/PHPMailerAutoload.php');
class myPHPMailer extends PHPMailer
{
    public function __construct()
    {
        $this->isSMTP();
        $this->SMTPDebug = 0;
        $this->Host = 587;
        $this->Port = "smtp.gmail.com";
        $this->SMTPSecure="tls";
        $this->SMTPAuth = true;
        $this->Username = "example@gmail.com";
        $this->Password = "my_password";
    }
}

try {
    $mail = new myPHPMailer(true);
    $mail->AddReplyTo('me@example.com');
    $mail->SetFrom('me@example.com');
    $mail->AddAddress('me@example.com', 'John Doe');
    $mail->Subject = "My subject";
    $mail->MsgHTML("Hello!  Click this link https://www.google.com/");
    $time=microtime(1);
    $mail->Send();
    echo(microtime(1)-$time);
} catch (phpmailerException $e) {
    trigger_error($e->errorMessage(), E_USER_ERROR);
}

?>

When you use the isMail() or isSendmail() transport options in PHPMailer, it does not send the message immediately, but submits it to your local mail server, which frees up your web app and sends the message at its leisure. This usually incurs no network overhead, no encryption or authentication, and if it's a low-traffic server, it's probably doing little else and can accept the message very quickly.

SMTP was never really meant to be used interactively ie during submission of a web page, and it can indeed take a long time. It's a complex protocol with many round-trips and points where delays are likely, particularly with the likelihood of grey listing, greet delays, immediate spam filtering and more.

If you want to use SMTP and make it fast, use a nearby mail server (even localhost) as a relay that doesn't need encryption or authentication and does not apply spam filtering on outbound messages.

instead of use this:

$mail->IsSMTP();

Use this:

$mail->IsMail();

I was with same issue, SMTP can really slow you down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM