PHPMailer Foreach Loop

£可爱£侵袭症+ 提交于 2021-02-10 12:15:32

问题


I currently am using PHPMailer which gets the list of email addresses from an uploaded .txt file. The current system works fine, but I am trying to add a tracking system to see if the email is viewed.

We are doing this by adding an image to each email which when viewed updates via php to let us know the email has been viewed.

Currently our PHPMail looks something like this,

foreach ($email_addresses as $line_num => $line) {
            $ismatch = preg_match('/^[\s,]+$/',$line);
            $isvalid = preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', trim($line));

            // found a blank line, ignore
            if($ismatch)
                echo "";

            // found an invaid email address, add to string
            else if($isvalid==0)
                $strInvalidEmailAddresses .= $line. '<br />';

            // no issues, add to BCC
            else{
                $mail->addBCC($line,$line); 
            }
}

The current system adds each email to BCC. I would like each email to be sent to each individual address without BCCing them.

I ran into issues when I tried this image to the end of the HTML email.

$track_image = '<img src="http://domain.com/email_test/email_beacon.php?campaign='.$intCampaignID.'&email='.$line.'" alt="" />';

$mail->MsgHTML($html_page.$track_image);

Whenever I try to include the tracking image, the $line (or email) is always the same, but I need it to change depending on which emails are in the .txt file.


回答1:


Instead of using BCC, you'd do something like:

... initialize PHP mailer ...
... set options common to ALL emails ...
foreach( ... loop over all recipients ...) {
    $mail->ClearAddresses(); // remove previous email addresses
    $mail->AddAddress($new_recipient_here);
    $mail->Body = <<<EOL
... customized html here
<img src="http://domain.com/email_test/email_beacon.php?campaign={$intCampaignID}&email={$address}" alt="" />
... more html here
EOL;

    $mail->send();
}



回答2:


Use ClearAllRecipients() to clears all recipients assigned in the TO, CC and BCC array. It returns void.




回答3:


The second issue is simply a forgotten $ -- it looks like your current example would throw a parse error. It should be:

$mail->MsgHTML($html_page.$track_image);

In order to send individual emails, instead of sending one email with a bunch of BCC's, you'd need to create a new $mail object each time inside the loop, instead of appending them all to a single $mail object which was already defined outside the loop.



来源:https://stackoverflow.com/questions/8451680/phpmailer-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!