Friday, October 23, 2009

Sending out MIME email with PHP Pear-Mail-Mime (build 1.5.2)

Recently on my adventure to write a backed to send out MIME (Multipurpose Internet Mail Extensions) email I ran into several obstacles.

My goal was simple. To write a PHP script that will be able to send out email with images embedded into the body.

The ending solution was using the PHP PEAR Object PHP-PEAR-Mail-Mime. You can install this package on a Linux system with pear command installed on it.

With root account, the command to install PHP-Pear-Mail-Mime libraries on Linux ssh console:
pear install Mail_Mime-1.5.2

Once you've installed the library you can find the location of Mail.php and mime.php by running the locate command:
locate Mail.php
locate mime.php

These two commands will give you the location of the Mail_Mime libraries.

This is the example that comes with the library.
http://pear.php.net/manual/en/package.mail.mail-mime.example.php

HTML version of email';
$file = '/home/richard/example.php';
$crlf = "\n";
$hdrs = array(
'From' => 'you@yourdomain.com',
'Subject' => 'Test mime message'
);

$mime = new Mail_mime($crlf);

$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');

//do not ever try to call these lines in reverse order
$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail =& Mail::factory('mail');
$mail->send('postmaster@localhost', $hdrs, $body);
?>


Goal one has been met: at this moment we are able to send out a MIME email.

Goal #2: Include the image in the body of the message. In order to reach this goal all we need to do is change the line
FROM

TO


and BADA-BING we have a simple prototype of a mail with image embedded into body.

No comments:

Post a Comment