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://

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
// define recipient
$recipient = '';
// define local path to excel file
$xlsFilename = 'report_for_boss.xlsx';
// define mail headers
$headers = array('From'       => 'Reporter <>',
                               '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.
    // 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.

Tags: , , , ,

Content not available.
Please allow cookies by clicking Accept on the banner

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.