Search code examples
phpcurlhtml-emailawstats

email script not formatting properly


I have this script that runs via a cron job once a month to send out awstats reports to clients. We've had to modify it recently because of tightening restrictions on our outbound mail server. Unfortunately some recipients are receiving the report as raw html code in the body of the message. Can anyone tell from the script where I went wrong?

    ########################## 
## Call to get awstats 
########################## 

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL,"http://www.$your_domain:2082/awstats.pl" 
        ."?month=$report_month&year=$report_year&output=main&config=$your_domain" 
        ."&lang=en&framename=mainright"); 
curl_setopt($curl, CURLOPT_USERPWD, "$user:$password"); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
//$attachment = curl_exec($curl); 
$attachment = "<br /><br /><div align=\"center\"><a href=\"$logo_link\"><img src=\"$logo_path\" border=\"0\" /></a>\n"; 
$attachment .= "<br /><font color=\"#FF0000\"><b>AwStats Report for $your_domain ($report_monthname $report_year)</b></font></div>\n";
$attachment .= "<base href=\"$awstats_img_path\">\n"; 
$attachment .= curl_exec($curl); 
curl_close($curl); 

########################## 
## Call to send email 
########################## 

$subject = "AwStats Report for $your_domain ($report_monthname $report_year)";
$header    = "From: " . $email_from . " <" . $email_from . ">\n";
$header .= "Reply-To: " . $email_from . "\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\n\n";
$uid = md5(uniqid(time()));
$message = "--" . $uid . "\n";
$message .= "Content-type:text/html; charset=iso-8859-1\n";
$message .= "Content-Transfer-Encoding: 7bit\n\n";
$message .= $attachment . "\n\n";
mail($email_to, $subject, $message, $header);

I've obviously left out the variable declarations here. But they are all in the code. I actually receive a cc of the message and it displays fine in Apple Mail on the desktop.

Thanks, CJ


Solution

  • You are missing the ending MIME boundary in the email which will cause some clients not to display it correctly.

    Add this as the last line before mail();

    $message .= "--{$uid}--\n"; // terminate mime boundary
    

    EDIT: After your comment I noticed another issue.

    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\n\n";
    $uid = md5(uniqid(time()));
    

    needs to be changed to:

    $uid = md5(uniqid(time()));
    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\n\n";
    

    The boundary was originally empty which might explain why some mail clients didn't show it properly.