4

I try with this, but no success:

$params = [
  'body' => 'My body',
  'subject' => 'My subject',
];

// I check by debug this code and $file get the right file
$file = File::load($myfile_id);

$attachment = [
  'filepath' => $file->getFileUri(),
];

$params['attachment'] = $attachment;

// This send a empty mail, without subject and not body
$send = \Drupal::service('plugin.manager.mail')->mail('mymodule', 'mykey', 'myuser@gmail.com', 'es', $params);

Why doesn't \Drupal::service('plugin.manager.mail')->mail work?

Then I tried this and it worked fine, but without attachments.

$system = \Drupal::service('plugin.manager.mail')->getInstance(array('module' => 'mymodule', 'key' => 'mykey'));

$file = File::load($myfile_id);

$params = [
  'headers' => [
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal',
  ],
  'to' => 'myuser@gmail.com',
  'body' => 'My body',
  'subject' 'My subject',
  // I try with:
  'attachment' => $file;
  // or
  'attachment' => ['filepath' => $file->getFileUri()];
  // with not success
];

// the mail was sent but without attachment
$send = $system->mail($params);

How do I send a mail with attachment on Drupal 8?

6

Drupal core doesn't support mail attachments/HTML mails.

You need to use an alternative mail implementation, like the Swift Mailer module.

Also, the reason the first implementation doesn't work is because you need to go through a hook_mail() implementation instead. See how core does it.

  • Webflo's Drupal 8 port of swiftmailer is now available at drupal.org/project/swiftmailer – sbrattla Nov 20 '15 at 9:56
  • I was trying to send HTML mails using SimpleNews. I had tried MimeMail, but couldn't get it to work. SwiftMailer is working perfectly. Thanks. – James Shields Sep 23 '16 at 12:38
  • Here is where there is an example for attaching files using SwiftMailer. – tzm Mar 22 '17 at 5:37

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.