Search code examples
phppear

PEAR Mail Sending CSV Fails


I'm having trouble sending a CSV using PEAR Mail in PHP. I can receive the message OK, and I can even open the CSV attachment -- but the contents show up as a base64 encoded string, rather than as a normal CSV.

Here's the relevant code, which outputs something like:

SUQsRW in the CSV that is attached.

Clearly not what I was going for!

// $csv is originally something like
// a,b,c,d,e
// d,e,f,g,h

$csv = base64_encode($csv);
$from = "...";
$to = "...";
$subject = "...";

$headers = array();
$headers['From'] = $from;
$headers['To'] = $to;
$headers['Subject'] = $subject;

// The attachment
$mime = new Mail_mime();
$mime->addAttachment($csv, "text/csv", "report.csv", false);
$mime->setTXTBody($bodyText);

$params = array();
$params['text_charset'] = 'utf-8';

$body = $mime->get($params);
$headers = $mime->headers($headers);

$smtp = Mail::factory('smtp', [unrelated server args]);
$mail = $smtp->send($to, $headers, $body);

Solution

  • So apparently you don't need to base64 encode the actual file contents. In any event, I still couldn't open the file in Excel it gave me the following error:

    SYLK: File format is not valid

    The solution is described here. According to the KB, it only applies to Excel for Mac, but I was seeing the error on Windows. In any event, the solution is correct, the CSV cannot begin with ID as the first two characters.