Drupal Technical
[Drupal] How to send an e-mail with an attachment in Drupal 7?
Most of us know how to send an e-mail with attachment. But do you know how you can do this using drupal 7? Not sure, then read on.
In this article, I am going to address 2 isssues.
- Sending an e-mail with an attachment.
- Sending an e-mail with multiple attachments.
Sending an e-mail in Drupal 7 with an attachment
The steps to be followed are:
- Step 1: Install and enable the modules MIME mail and Mail system.
- Step 2: Define hook_mail() in your custom module.
The synatx is as follows:
<?php
function mymodule_mail($key, &$message, $params) {
if (isset($params['subject'])) {
$message['subject'] = $params['subject'];
}
if (isset($params['body'])) {
$message['body'][] = $params['body'];
}
if (isset($params['attachment'])) {
$message['params']['attachments'][] = $params['attachment'];
}
}
?>
This step defines the parameters to be sent as part of a mail.
- Step 3: Now that we've defined the mail function , the next step is to call the function with proper parameters.
In order to call the hook_mail() , I am creating a send _mail (). Inside this function , we have to declare and define the variables which are to be passed to the mail function.
<?php
function mymodule_send_mail () {
$to =$user->mail;//gets the current user's mail address
$from = variable_get('site_mail', ''); //admin's mail address
$body = 'This is a test mail';
$attachment = array(
'filecontent' => file_get_contents(DRUPAL_ROOT . '/' . filename),
'filename' => 'filename.pdf';// You can change the name and extension of the file you need to send.
'filemime' => 'text/plain',
);
$message = drupal_mail('mymodule, 'message_key', $to, user_preferred_language($user), array('body' => $body, 'subject' => $subject, 'attachment' => $attachment), $from, TRUE); /* calls the mail functionality with parameters.
?>
Sending an e-mail with multiple attachments
If you want to send multiple files as attachments,
- step 1: Add the below code to the hook_mail function.
<?php
$message['params']['attachments'][] = $params['attachment2'];
?>
- step 2 : Modify the mymodule_send_mail() by adding the second attachment variable.
<?php
$attachment2= array(
'filecontent' => file_get_contents(DRUPAL_ROOT . '/' .'filename'),
'filename' => 'file.jpeg', //Name of the file
'filemime' => 'image/jpeg',//extension
);
?>
- step3 : Add $attachment2 to the drupal_mail().
<?php
$message = drupal_mail('churchpress', 'message_key', $to, user_preferred_language($user), array('body' => $body, 'subject' => $subject, 'attachment' => $attachment,'attachment2'=>$attachment2), $from, TRUE);
?>
The above code worked for me. Hope this works for you too.!!!
References: http://blog.rapiddg.com/2012/02/drupal-7-html-e-mail-with-pdf-attachmen…