Sending Emails with Attachments using Messaging Framework in Drupal
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'] = 'me@example.com';
$message['to'] = 'you@example.com';
// 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.

It is important to note that
It is important to note that the function does not check the file path parameter.
For security reasons, if you are taking the file from a form input (ie: send me this file via email), the function should do a basic check between $_SERVER['DOCUMENT_ROOT'] and the realpath of the argument.
You do not want your function to email the /etc/passwd file after all.
Post new comment