A PHP script to send email with an attachment

PHP email FAQ: How do I send email from a PHP script? (Including sending email with an attachment.)

Continuing with my initiation into the PHP programming world, I just finished developing a PHP script to send a mail message with an arbitrary attachment. (I write 'arbitrary' there because a lot of the example PHP mail scripts I've seen focus on attaching an image, and I'm not really familiar with MIME types yet, and "image/jpg" wasn't working for my needs.)

PHP send mail/email + attachment script

So, without any more introduction, here's a PHP script that sends a mail message with an attachment:


// a php script to send an email with an attachment
// author: alvin alexander, devdaily.com

require 'Mail.php';
require 'Mail/mime.php';

// static fields
$subject = 'An email message with an attachment';
$text    = 'The text version of my message.';
$html    = '<html><body>The HTML version of my message.</body></html>';

// dynamic fields
$file    = 'my-attachment.zip';

// script begins

$headers['From'] = $from;
$headers['Subject'] = $subject;

$mime = new Mail_mime;


// defaults to 'application/octet-stream' if i don't specify.
// @see http://pear.php.net/manual/en/package.mail.mail-mime.addattachment.php
//$mime->addAttachment($file, 'image/png');

// never call these in reverse order
// @see http://pear.php.net/manual/en/package.mail.mail-mime.example.php
$body = $mime->get();
$headers = $mime->headers($headers);

$message =& Mail::factory('mail');
$message->send($to, $headers, $body);


PHP email/attachment script - notes

The only real tricks to this PHP email attachment script are are (a) knowing that these PEAR packages exist; (b) installing those packages (I ran into a couple of problems, and had to install them manually, including their dependencies); and (c) then knowing which MIME type to use.

As you can see from the PHP code above, I'm just letting the MIME type default to "application/octet-stream", but if anyone knows a better way to do this, I'll be happy to hear about it. My only caveat is I don't want to hard-code a MIME type here, I'd rather let the system determine the MIME type dynamically, if possible.

I hope this "PHP send mail and attachment" example script will be helpful to other developers. Feel free to leave a comment below if you have any questions or suggestions.