Send HTML mail with attachment using Pear’s Mail
To send proper HTML e-mails, with attachments and other features, it’s best to use PEAR’s Mail_Mime package. You can easily install this package using pear binary included in PHP distribution.
You might also have to install PEAR Mail package using the command pear install Mail_mime.
:~# pear install Mail_mime downloading Mail_Mime-X.Y.Z.tgz ... Starting to download Mail_Mime-X.Y.Z.tgz (31,337 bytes) .....done: 31,337 bytes install ok: channel://pear.php.net/Mail_Mime-X.Y.Z :~#
Mail_mime package is installed. In default PHP configuration, when you have PEAR installed, PEAR include directory will already be configured in include_path, so you can simply include Mail/mime.php script, and you have Mail_mime ready for use.
Here’s an example on how to compose HTML and plain text e-mail message with one Excel report as attachment (you might have created it with PHP Excel writer).
// require PEAR Mail and Mail_mime classes require('Mail.php'); require('Mail/mime.php'); // define recipient $recipient = 'boss@example.com'; // define local path to excel file $xlsFilename = 'report_for_boss.xlsx'; // define mail headers $headers = array('From' => 'Reporter <reporter@example.com>', 'To' => $recipient, 'Subject' => 'Report for boss' ); $mime = new Mail_mime("\n"); // if client reading this mail, reads only text-part (or cannot read HTML messages), // he'll see this text body message $mime->setTXTBody('This is a text part of the message.'); // if client reading this email, reads HTML (multi-part) messages, // he'll see this HTML body message $mime->setHTMLBody('<html><body>This is the HTML part of the message</body></html>'); // now, we'll add local file as an attachment. Second argument is a mime type // specification for XLSX filetype. $mime->addAttachment($xlsFilename, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $xlsFilename); // get body of the e-mail message from Mail_mime class. $body = $mime->get(); // get headers $hdrs = $mime->headers($headers); // now, lets send e-mail using the PEAR Mail class. $mail = Mail::factory('mail'); $mail->send($recipient, $hdrs, $body); // that's it!
This is the basic all-in-one example on how to send multi-part e-mail messages. You can also add images to e-mail, etc. You can read more about PEAR Mail_mime class here.