16.2.1. ProblemYou want to send MIME email. For example, you want to send multipart messages with both plain text and HTML portions and have MIME-aware mail readers automatically display the correct portion. 16.2.2. SolutionUse the Mail_mime class in PEAR: require 'Mail.php'; require 'Mail/mime.php'; $to = 'adam@example.com, sklar@example.com'; $headers['From'] = 'webmaster@example.com'; $headers['Subject'] = 'New Version of PHP Released!'; // create MIME object $mime = new Mail_mime; // add body parts $text = 'Text version of email'; $mime->setTXTBody($text); $html = '<html><body>HTML version of email</body></html>'; $mime->setHTMLBody($html); $file = '/path/to/file.png'; $mime->addAttachment($file, 'image/png'); // get MIME formatted message headers and body $body = $mime->get(); $headers = $mime->headers($headers); $message =& Mail::factory('mail'); $message->send($to, $headers, $body); 16.2.3. DiscussionPEAR's Mail_mime class provides an object-oriented interface to all the behind-the-scenes details involved in creating an email message that contains both text and HTML parts. The class is similar to PEAR's Mail class, but instead of defining the body as a string of text, you create a Mail_mime object and call its methods to add parts to the body: // create MIME object $mime = new Mail_mime; // add body parts $text = 'Text version of email'; $mime->setTXTBody($text); $html = '<html><body>HTML version of email</body></html>'; $mime->setHTMLBody($html); $file = '/path/to/file.txt'; $mime->addAttachment($file, 'text/plain'); // get MIME formatted message headers and body $body = $mime->get(); $headers = $mime->headers($headers); The Mail_mime::setTXTBody( ) and Mail_mime::setHTMLBody( ) methods add the plain text and HTML body parts, respectively. Here, we pass in variables, but you can also pass a filename for Mail_mime to read. To use this option, pass TRue as the second parameter: $text = '/path/to/email.txt'; $mime->setTXTBody($text, true); To add an attachment to the message, such as a graphic or an archive, call Mail_mime::addAttachment( ): $file = '/path/to/file.png'; $mime->addAttachment($file,'image/png'); Pass the function to the location to the file and its MIME type. Once the message is complete, do the final preparation and send it out: // get MIME formatted message headers and body $body = $mime->get(); $headers = $mime->headers($headers); $message =& Mail::factory('mail'); $message->send($to, $headers, $body); First, you have the Mail_mime object provide properly formatted headers and body. You then use the parent Mail class to format the message and send it out with Mail_mime::send( ) . 16.2.4. See Also16.1 for sending regular email; 16.3 for more on retrieving mail; the PEAR Mail_Mime class at http://pear.php.net/package-info.php?package=Mail_Mime. |