How to Send Email with an Attachment from Drupal

By: Michael Phipps

23 Jun 2009

The default drupal_mail() function does not include an attachment functionality.  Searching the Internet lots of people suggest using the mimemail module but do not offer suggestions as to HOW it can be used from your code.

I found this documentation patch for mimemail, which helped clarify what is actually required: http://drupal.org/files/issues/mimemail.module.documentation.patch

My interpretation of that is:

$attachments[]=array(         
'filepath' => '/path/to/file.name',
'filemime' => 'mime/type',
);

mimemail($sender,
$recipient,
$subject,
$body,
$plaintext = NULL,
$headers=array(),
$text = NULL,
$attachments = array(),
$mailkey = '');














I’ll update this post with a bit more information once I’ve tested this, and provide a better working example.  I don’t like that mimemail is only out of beta in Drupal 5.0 but I’ve not found any other suitable solutions.  Email attachments should be in core from my point of view, but I’m sure there is a reason the are not.

UPDATE:

I’ve sinced tried this code in a commercial project with great success.

Things to look out for:

  • You must download and enable the mimemail module to access the mimemail function from your code
  • The emails mimemail sends are themed using your CSS.  I add an override function to my template.php file that was a bit like this
    function phptemplate_mimemail_message($body, $mailkey = null){

    return $body;

    }







I still don’t think I’ve provided a good enough example to clearly demonstrate how to use mimemail, so I’ll put together a small, complete module that you can use to demo mimemail in a day or so (just a bit under the pump at the moment)