Drupal 7 : Programmatically send Mail with attachment with Sample code

In Drupal 7 we can send mail using the function drupal_mail(). It help to sent mail from our Drupal system. This function need mail module, mail key, to mail id, from id, mail language and parameters with mail subject and message body.

Syntax: 

drupal_mail($module, $key, $email, $language, $params, $from, $send);

$module - Module that send mail.

$key - Unique Key identifying mail.

$language - Message language.

$param - Contains mail subject and body.

$from - From mail Id

$send -Boolean value True or False.

Example: 

$from = variable_get('site_mail', '');
$module = 'MODULE_NAME';
$language = language_default();
$params = array();
$report = "This is Sample mail content for testing purpose";
$send = FALSE;
$key = 'MAIL_UNIQUE_KEY';
$email = "username@example.com";
$message = drupal_mail($module, $key, $email, $language, $params, $from, $send);
$message['subject'] = 'Mail Subject';
$message['body'] = array($report);
$system = drupal_mail_system($module, $key);
$message = $system->format($message);
$message['result'] = $system->mail($message);

Drupal send mail with attachment:

To Send mail with attachement we can add parameter for mail with “attachment” array. This attachment array contains File path, Filename and File Mime type. This example show how to send mail with attachement.

Example: 

$from = variable_get('site_mail', '');
$module = 'MODULE_NAME';
$language = language_default();
$params = array();
$file = file_load(FILE_ID); // File Id from Drupal file system.
$report = "This is Sample mail content for testing purpose";
$send = FALSE;
$key = 'MAIL_UNIQUE_KEY';
$email = "username@example.com";
$message = drupal_mail($module, $key, $email, $language, $params, $from, $send);
$message['subject'] = 'Mail with Attachment';
$message['body'] = array($report);
$message['params']['attachments'][] = array(
  'filepath' => $file->uri,
  'filename' => $file->filename,
  'filemime' => $file->filemime,
  'list' => TRUE,
);
$system = drupal_mail_system($module, $key);
$message = $system->format($message);
$message['result'] = $system->mail($message);
Category: