[Drupal] How can we send mails in Drupal 6 with attachments?
While working on a Drupal 6 project, I came across the requirement to send some mails. Interestingly, I couldn't find any good articles or procedures on the same. So, here, I am going to explain how to send mails in Drupal 6 with attachments. If you need any business support, get in touch immediately.
Implement hook_mail function
First of all, you have to implement the hook hook_mail in your custom module. This hook handles the common things related to different mails. It also allows us to set subject and body according to the mail keys.
hook_mail($key, &$message, $params);
Here the $key can be used to uniquely identify different mails. The $message will contain the message of the mail(not needed in the mail body, it can be build inside this hook, under corresponding $key). The $params contain the different parameters to the mail. This hook will be called whenever the mail functions like drupal_mail or mime_mail(mimemail module) etc is called.
Need of hook_mail?
Usually, the mails can be send by just calling drupal_mail or other mail sending functions. But the hook_mail will help you to alter the mail properties like headers, subject or to add attachments to the mail array. Thus, extra attributes can be added by using this hook.
Also in this hook it is possible to alter the contents or add headers according to the different key values. Thus we can handle multiple mail sending function calls from this hook implementation.
Sending attachments with a mail
To send an attachment with a mail you can use the following code. There is bug in Drupal due to which the files with absolute paths will not be sent correctly as attachments. There are proposed solutions, but you can give the absolute file path with the filename parameter which will help to attach the file correctly. However, the problem is that the full file path will be displayed in the mail received.
$attachments = array( 'filecontent' => file_get_contents($full_file_path), 'filename' => <full_file_path>, 'filemime' => 'text/csv', );
After this, you need to add the attachments array to the attachments key of the $message in hook_mail.
$message['attachments'] = $params['attachments'];
If there is another attachment, it can be added as another array element to the attachments array. The only thing you need to be careful is that the filename should be given with full path. For more details on the same, please contact us.