PHPMailer不会覆盖$ mail-> Body in Loop

时间:2018-01-20 22:34:23

标签: php phpmailer sendmail

我正在使用循环向客户发送电子邮件。

Body(电子邮件)在循环中与来自MySQL数据库的客户端数据(例如名称等)合并,以个性化电子邮件。

问题是每封电子邮件都是使用相同的Body发送的。 PHPMailer在循环的每次迭代中都不会使用新的合并消息覆盖Body。

示例:

foreach ($recipients as $recipient) { f
    $message = "Hello " . $recipient->fname . ' ' . $recipient->lname . "...."
    // remainder of code below....
}

将所有电子邮件发送给" Hello Jane Doe ...."

以下是我正在使用的代码

$maillist = new maillist; // this is a custom class
$mail = new PHPMailer;

$mail->isSendmail();
$mail->isHTML(true);   
$mail->ClearAllRecipients();

// message body and subject
$subject = "This is the subject";
$message_body = "Hello {fname} {lname}.... ";

// set the sender info
$sender_email = "support@mydomain.com"; 
$sender_name = "My Website Name";

// get the recipients for the email from a function in the maiilist class
$recipients = $maillist->selectRecipients();

foreach ($recipients as $recipient) { 

    $id = $recipient->id;
    $fname = $recipient->fname; // Recipient first name
    $lname = $recipient->lname; // recipient last name
    $email = $recipient->email; // recipient email address

    // merge the reipient data into message
    $before = array("{fname}", "{lname}");
    $after = array($fname, $lname);
    $message = str_replace($before, $after, $message_body);

    // send the email using PHPMailer
    $mail->setFrom($sender_email, $sender_name);
    $mail->addAddress($email);      
    $mail->addReplyTo($sender_email);
    $mail->Subject = $subject;
    $mail->Body = $message;
    $email_message = $mail->send(); 
    $mail->ClearAllRecipients();

    // log sent message in database
    if ($email_message) {
        $maillist->logMessage($id, $email, $subject, $message);
    }
}

0 个答案:

没有答案