user256968
user256968

Reputation: 371

PHPMailer executing around 2 seconds

I was following PHPMailer tutorial and some tutorials in Internet but I still can't make execution less than 2 second. On many website it says it shouldn't take more than 0.4s. I tried it from my local machine and from AWS machine. Execution time same.

class BatchMailer {
    private static $mail;
    private static $initialized = false;

    private static function initialize() {
        if (self::$initialized)
            return;

        self::$mail = new PHPMailer;
        self::$mail->SMTPDebug = 2;
        self::$mail->isSMTP();
        self::$mail->Host = 'smtp.gmail.com';
        self::$mail->Port = 587;
        self::$mail->SMTPSecure = 'tls';
        self::$mail->SMTPAuth = true;
        self::$mail->Username = '***';
        self::$mail->Password = '***';
        self::$mail->SMTPKeepAlive = true;
        self::$mail->setFrom('***@gmail.com', 'Title');
        self::$mail->isHTML(true);
        self::$mail->AltBody = 'Please use an HTML-enabled email client to view this message.';
        self::$initialized = true;
    }

    public static function setSubject($subject) {
        self::initialize();
        self::$mail->Subject = $subject;
    }

    public static function setBody($body) {
        self::initialize();
        self::$mail->Body = stripslashes($body);
    }

    public static function sendTo() {
        self::initialize();
        self::$mail->clearAddresses();

        $recipients = array(
            '***@gmail.com' => 'Person One'
        );

        foreach($recipients as $email => $name) {
            self::$mail->AddCC($email, $name);
        }

        self::$mail->send();
        return;
    }

    static function test() {
        self::setSubject('subject');
        self::setBody('body');
        self::sendTo();
    }
}

Upvotes: 1

Views: 287

Answers (1)

Synchro
Synchro

Reputation: 37730

SMTP is often slow, especially when things like greetdelay/tarpitting are used as anti-spam measures. 2 seconds is not that slow - the SMTP spec allows for timeouts of 10-20 minutes! It's really unsuited to real-time use, i.e. during a web page submission, but that doesn't seem to stop many trying to use it that way. To maximise performance you can install a local mail server to use as a relay, or hand off your message send to a separate process that doesn't mind waiting for a while, for example by submitting using an async ajax request from your page so the user is not blocked from doing other things.

If you're sending larger volumes of email it's important to use a relay and SMTP keepalive while submitting it. I have no trouble sustaining over 200 messages/second with PHPMailer.

Nice class BTW - tidier than most of the things I see on SO! $initialized is not needed - just check whether self::$mail is set instead.

Upvotes: 3

Related Questions