PHP Add string attachment with Pear Mail

Pear Mail is an old library but still in use by many for its simplicity. Adding a file attachment is pretty straightforward.

But, adding an attachment from a string containing data (such as a CSV file) is not documented well.

The trick is in the 4th parameter to addAttachment.
// get records from a database here.  This line will vary depending on your db query method
$people = $database->get_results( $sql, ARRAY_A);

// create header csv row
$csv = array2csv(array('First', 'Last', 'Title', 'Email', 'City', 'State'));

// populate csv string
foreach ($people as $person)
	$csv .= array2csv($person);


$crlf = "\n";
$to = '[email protected]';

$smtpinfo["username"] = "[smtp username]";
$smtpinfo["password"] = "[smtp password]";
$smtpinfo["host"] = "[smtp host]";
$smtpinfo["port"] = "587";
$smtpinfo["auth"] = true;
$headers = array("From" => "Me <[email protected]>", 
				 "Subject" => 'People Report',
				 "Reply-To" => "[email protected]",
				 "To" => $to
);
 				 
 				 
$body = 'We have ' . count($people) . ' in this report.'; 				


// send email
$mime = new Mail_mime($crlf);	 

$mime->setTXTBody(strip_tags($body));
$mime->setHTMLBody($body);


// the magic is in the 4th parameter.  It tells addAttachment to treat $csv as a string, not a filename
$mime->addAttachment($csv, 'text/csv', 'people-listings.csv', false);


$body = $mime->get();
$headers = $mime->headers($headers);
$mail =& Mail::factory("smtp", $smtpinfo); 


$mail->send($to, $headers, $body);	 
			




function array2csv($fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
{
    $buffer = fopen('php://temp', 'r+');
    fputcsv($buffer, $fields, $delimiter, $enclosure, $escape_char);
    rewind($buffer);
    $csv = fgets($buffer);
    fclose($buffer);
    return $csv;
}
Posted by
Snippet Viewed 6792 times.

Share your PHP code snippets:

  • Get some recognition & a link back to your site.
  • Create your own code library.
  • Help your fellow developers, as they have helped you.

 

Submit | Browse

Most Recent php snippets

Most Viewed