php - 使用 PHP 发送的邮件花费太多时间

标签 php performance phpmailer

我用 PHP 编写了一个类,用于使用 Gmail 帐户发送邮件。此类又使用 PHPMailer 库。 Windows Vista 上的设置是 WAMP 2.4。使用 PHP 中的 microtime() 函数,我发现发送一封邮件需要 5 到 6 秒的时间。对于在我必须花费多达 5-6 秒才能发出一封邮件的那种设置上运行的 PHP 脚本,这是否正常?这是该类的代码。

<?php

require_once("phpmailer/class.phpmailer.php");
require_once("phpmailer/class.smtp.php");

class Mailer {

    // Needs to be set per object
    public $subject;
    public $message;
    public $to_name;
    public $to;

    private $mail; // This is the main mail object that'll be initialized 

    public function __construct() {

        // Need to create a PHPMailer object in the constuctor and return it for use in this class. 

        $mail = new PHPMailer();

        $from_name = "bleh";
        $from = "bleh@gmail.com";
        $username = "bleh";
        $password = "bleh";

        $mail->FromName = $from_name;
        $mail->From = $from;
        $mail->Username = $username;
        $mail->Password = $password;

        $mail->IsSMTP();
        $mail->Host = "smtp.gmail.com";
        // $mail->Port = 587; // Turns out, I dont need this one. 
        $mail->SMTPAuth = true; // gmail requires this
        $mail->SMTPSecure = 'tls'; // gmail requires this

        $this->mail = $mail;


    }


    function send() {

        $mail = $this->mail; // The mail object 

        $mail->Subject = $this->subject;
        $mail->Body = $this->message;
        $mail->AddAddress($this->to, $this->to_name);

        $result = $mail->Send();
        return $result;

    }
}
?>

用于测试的代码 -

$startTime = microtime(true);
require_once("mailer.php");

$mailer = new Mailer();

$mailer->subject = "Test";
$mailer->message = "Test";
$mailer->to_name = "My Name";
$mailer->to = "anemail@address";

$mailer->send();
echo "Time:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

最佳答案

SMTP 花费很长时间是很常见的 - 它甚至以 greetdelay/tarpit mechanisms 的形式用作反垃圾邮件措施. RFC2821 section 4.5.3.2在流量开始之前允许最多 5 分钟的延迟。 SMTP 不适用于交互式使用(因为它不能在那种情况下排队),因此在网页提交期间通过 SMTP 发送可能会因此受到影响。通过异步进程发送邮件或 SMTP 可以避免这个问题。

在 PHPMailer 中,您可以启用 SMTP 调试输出,它会向您显示正在发生的事情,这样您就可以看到是什么占用了时间:

$mail->SMTPDebug = 2;

关于php - 使用 PHP 发送的邮件花费太多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23047169/

相关文章:

php - 将表详细信息复制到具有更新值的同一表 - MySql

PHP:高级 ORDER BY

c++ - 这段代码会在每次迭代时获取元素吗?

php - 使用 PHPMailer 的文件附件

codeigniter - 通过 sendgrid 发送的纯文本电子邮件中的额外换行符

php - MySQL PHP - 选择 WHERE id = array()?

php - 如何使 PHP 代码只运行一次

iphone - 在 UIScrollView 中按需加载 UITableView 中的单元格

c++ - 用于 OpenGL 图形的 C 或 C++

html - @font-face 只对内联字体系列不起作用