6

I am not able to send mails with an attachement using the MIME Mail module.
There isn't munch documentation about this module, but some people claim they have successfully used the module, and sent a mail with an attachment.

I've enabled and successfully configured:

I think I configured the modules correctly.

screenshot

No mail with attachement is delivered. I call drupal_mail() in a cron job with the following code.

drupal_mail('mymodule', 'notice', $user_email, $lang, $params, $admin_email);

It should invoke any hook_mail() implementations, which it does, but without the attachment.

function mymodule_mail($key, &$message, $params) {
  $data['user'] = $params['from'];
  $account = $data['user']->name;

  $file_content = file_get_contents('some/file/path');

  $attachments = array(
     'filecontent' => $file_content,
     'filename' => 'example-' . $account,
     'filemime' => 'application/pdf',
   );

  switch($key) {
    case 'notice':

      $langcode = $message['language']->language;
      $message['subject'] = 'example submission from '. $account;
      $message['body'][] =
        '<p>'. $account .' has submitted an example.</p>';
      $message['params']['attachments'][] = $attachments;
      break;
  }
}
  • concept behind this workflow is that a file link attached to mail(file uploaded to server and its link given). – monymirza Mar 14 '13 at 12:12
  • Eum... What's the point you're trying to make? – Michiel Mar 14 '13 at 12:36
3

The solution I've found is to use hook_mail_alter to attach the file to the email after it's generated and before it's sent. The key to that is making an array of details about your attachment and adding that to $message['params']['attachments'].

hook_mail will send mail, but if you're using another program to send (Swift Mailer or PET), then I believe you'll need hook_mail_alter to alter the mail instead of sending it yourself.

I also suggest using the Form API (also this) to keep track of your file. That's not required, however, just provide the necessary info.

function myhook_mail_alter(&$message) {

  print "message id: {$message['id']}\n";

  // if this email is one of the ones I want to alter:
  if (!empty($message['id']) && (preg_match('/^message-id-set-by-formmail[\d]{1,2}/', $message['id']))) {

    // $message['params']['body'] is a single string, not an array
    $result = preg_match('/\[my dumb string with node id# (\d+)]/', $message['params']['body'], $matches);

    print "Message body: \n {$message['params']['body']} \n\n Matches:\n";
    print_r($matches);

    if (!empty($matches[1])) {
      $file_id = $matches[1];
      $my_pdf = file_load($file_id);
      $original_attachments = $message['params']['attachments'];
      // $original_attachments is an array of associative arrays, each bearing details about an attachment.
      // Add an associative array about this desired attachment.
      $my_attachment = array(
        'filecontent' => file_get_contents($my_pdf->uri),
        'filemime' => $my_pdf->filemime,
        'filename' => $my_pdf->filename,
        'filepath' => NULL,
      );
      $message['params']['attachments'][] = $my_attachment;
    }

  }
}
2

My working Drupal 7 solution with module MimeMail without invoking hook_mail():

// Load attachment.
$file = file_load($fid);

$to = 'something@email.com';
$from = 'something@email.com';
$subject = 'Invoice ' . $file->filename;

$module = 'mimemail';
$token = time();

$message = array(
  'id' => $module . '_' . $token,
  'to' => $to,
  'subject' => $subject,
  'body' => array('something text...'),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8',
  ),
  'params' => array(
    'attachments' => array(
      0 => array(
        'path' => file_stream_wrapper_get_instance_by_uri($file->uri)->realpath(),
        'filecontent' => file_get_contents($file->uri),
        'filename' => $file->filename,
        'mime' => $file->filemime,
        'encoding' => 'base64',
        'disposition' => 'attachment',
        'list' => TRUE,
      ),
    ),
  ),
);

$system = drupal_mail_system($module, $token);
$message = $system->format($message);

if ($system->mail($message)) {
  return TRUE;
}
else {
  return FALSE;
}
1

Try this, it should work, good luck!

function mymodule_mail($key, &$message, $params) {
  $data['user'] = $params['from'];
  $account = $data['user']->name;

  $file_content = file_get_contents('some/file/path');

  $attachments = array(
     'filecontent' => $file_content,
     'filename' => 'example-' . $account,
     'filemime' => 'application/pdf',
   );

  switch($key) {
    case 'notice':

      $langcode = $message['language']->language;
      $message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
      $message['subject'] = 'example submission from '. $account;
      $message['body'][] =
        '<p>'. $account .' has submitted an example.</p>';
      $message['params']['attachments'][] = $attachments;
    $system = drupal_mail_system($module, $key);
    // Format the message body.
    $message = $system->format($message);
    // Send e-mail.
    $message['result'] = $system->mail($message);

    if($message['result'] == TRUE) {
        drupal_set_message(t('Your message has been sent.'));
    }
    else{
        drupal_set_message(t('There was a problem sending your message and it was not     sent.'), 'error');
    }
      break;
  }
}
0

Swift Mail has a nice documentation on this, check this out. And below I did a small custom function to grab the full uri path of the attachments.

/**
 * Send an e-mail.
 */
function test() {

  //load the file by fid
  $file_one = file_load(1);

  //create the file details manually.
  $file = new stdClass();
  $file->uri = file_create_url($file_one->uri);
  $file->filename = $file_one->filename;
  $file->filemime = $file_one->filemime;

  if (!empty($file)) {
    // set parameters
    $params = array(
    'subject' => $subject,
    'body' => $body,
    'to' => $to,
    'cc' => $cc,
    'files' => array($file)
    );
  }
  // Send message
  $message = drupal_mail('singtel_kms', 'send', $to, language_default(),$params);

  // Check the email result array to make sure an email was sent.
  if(!empty($message['result'])) {
     drupal_set_message(t('Your email has been sent.'));
  } else {
     drupal_set_message(t('There was a problem with the application. Please send again or contact administrator.'), 'error');
  }
}

In your hook_mail()

/**
 * Implementation of hook_mail().
 */
function modulename_mail($key, &$message, $params) {

  switch($key) {
    default:
        $text[] = t('<strong>Hi</strong>');
        $text[] = t('<p>This is an e-mail.</p>');

        if (isset($message['params']['files'])) {
            $message['params']['files'][] = $params['files'];
        }

        $message['subject'] = t('Test');
        $message['body'] = $text;
        break;
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.