Sending Emails with Attachments using Messaging Framework in Drupal

0 min read

Francis Pilon

Recently, a client of ours asked us to provide functionality to their site that would automatically send out emails with an attachment on a regular basis. Quick research on email file attachments with Drupal proved to be very slim and inconclusive until I caught a related thread for the Notifications Add-ons project.

Turns out sending out emails with attachments is a pretty simple job when using the Messaging Framework in combination with PHPMailer. Once you have enable the Messaging and Messaging PHPMailer modules, setup the appropriate permissions and configured the administrative options, you will have access to the messaging_phpmailer_drupal_mail() function. This function mimics drupal_mail but instead sends your message via PHPMailer giving you the additional ability to attach files.

Here's a function taken from the custom module we built that makes use of messaging_phpmailer_drupal_mail():

function my_mail($filepath) { // Basic info $message['subject'] = t('Hello World!'); $message['body'] = t('Please see that attached file.'); $message['headers']['From'] = '[email protected]'; $message['to'] = '[email protected]'; // Attachment object $att = new stdClass(); $att->filepath = $filepath; $att->filename = 'order.csv'; $att->filemime = 'application/octet-stream'; $message['attachments'][0] = $att; // Using messaging_phpmailer to send our message $rtn = messaging_phpmailer_drupal_mail($message); // Error handling goes here. See: http://drupal.org/node/688594 // Yay! watchdog('My', 'Order sent.'); return TRUE; }

Note that the file path is passed as a function argument and should be the full path to your file from the root of your file system. For example: /var/orders/orders.csv. Also, make sure that your web server user has the proper permissions access to the file.

Happy coding!