PHPMailer循环通过电子邮件的最佳解决方案

时间:2014-06-02 12:09:25

标签: php email sendmail phpmailer

我正在尝试建立一个召回系统,根据指定的标准向用户发送提醒电子邮件。目前,我可能每周会一次发送10-15个提醒,但未来可能每周会增加到数百个提醒。我决定使用PHPMailer类来处理邮件发送,但我是PHPMailer的新手,因此我不确定我提出的解决方案是否会提供最佳性能,或者我的代码是否可以改进。此外,我存储了电子邮件发送成功后的日期。

这就是我的想法:

<?php
//I have left out the database connection details for obvious reasons

require 'PHPMailer-master/PHPMailerAutoload.php';

$result = mysql_query("SELECT * FROM patients_test WHERE recall <> 0 AND DATE_ADD(`last_seen`, INTERVAL recall DAY) < DATE_ADD(NOW(), INTERVAL 21 DAY)");


while($row = mysql_fetch_array($result))
{
    //Create new mail object
    $mail = new PHPMailer;

    ///Mail settings
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'host.co.uk';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'myusername';                 // SMTP username
    $mail->Password = 'mypassword';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

    $mail->From = 'myusername';
    $mail->FromName = 'Mailer';
    $mail->addReplyTo('replytoadd', 'Information');

    $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = 'Reminder email';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    //Recipient info
    $ref = $row['identifier'];
    $first_name = $row['first_name'];
    $surname = $row['surname'];
    $email = $row['email'];


    $mail->addAddress($email, $first_name." ".$surname);     // Add a recipient
    if(!$mail->send())
    {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    }
    else
    {
        echo 'Reminder sent to '.$first_name.' '.$surname.' successfully<br/>';

        mysql_query("UPDATE patients_test SET last_reminder= CURDATE() WHERE identifier='$ref'");//Update database to show that email has been sent
        $mail->clearAllRecipients();
    }
}

?>

我选择不使用PHP默认 mail()功能的原因是因为我担心我的电子邮件会被阻止为垃圾邮件而我在某处读到使用像PHPMailer这样的东西可以减少这种情况发生的可能性。有没有人对这个问题有任何建议?

提前致谢 富

1 个答案:

答案 0 :(得分:0)

填写邮件标题可以减少此问题。邮件服务器有一些规则来定义邮件是否是垃圾邮件。此外,通过循环发送邮件可能会导致阻塞,具体取决于它的配置方式。