我用PHP编写了一个类,用于发送使用Gmail帐户的邮件.该类又使用PHPMailer库.该设置是Windows Vista上的WAMP 2.4.使用PHP中的microtime()函数,我发现发送一封邮件需要5到6秒.在这种设置上运行的PHP脚本是否正常,我需要花费5-6秒才能发送一封邮件.这是该类的代码.
<?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;