Search code examples
emailmimepearoverwrite

PEAR Mail, Mail_Mime and headers() overwrite


I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.

Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.

To be exact: The problem is

$mime->headers($headers, true);

As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.

I'm really going crazy about this thing... any suggestions?

(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)

Code:

// sql query and if num_rows > 0 ....

require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');

ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();

ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();

$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;

$mail =& Mail::factory('smtp', $XY['mail']['params']);

$headers = array();
$headers['From'] = 'XY <[email protected]>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <[email protected]>';

ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();

$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
    $html = $head . $template . $foot;

    $mime->setHTMLBody($html);

    #$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to [email protected]
    $to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <[email protected]>';
    $headers['To'] = $to; // Sets to in headers to a new

    $body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
    $hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user

    $sent = $mail->send($to, $hdrs, $body);
    if (PEAR::isError($sent)) {
        errlog('error while sending to user_id: '.$row['id']); // personal error function
    } else {
        // Write log file
    }
}   

Solution

  • There is no reason to keep the old object and not creating a new one. Use OOP properly and create new objects - you do not know how they work internally.