Jun 27, 2019 in Drupal 8, Snippets

First, somewhere you would call the hook_mail() function. This can be after submitting a form, a node, or some other event. 

// The data below you would get programmatically after submitting a form, node, ... whatever
$orderData = [
  'invoice_id' => 5, // this is the file fid
  'to' => 'customer@example.com'
  'name' => 'Customer name'
];
$subject = t('Your invoice at our store');
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'mymodule';
$key = 'invoice';
$to = $orderData['to'];
$params['message'] = $orderData;
$params['title'] = $subject;
$langcode = NULL;
$send = TRUE;

$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $options = [
    'langcode' => $message['langcode'],
  ];
  switch ($key) {
    case 'invoice':
           
      if ($params['message']['invoice_fid']) {
        $invoice_pdf = File::load($params['message']['invoice_fid']);
        $invoice_file = (object) [
          'filename' => 'custom_invoice.pdf',
          'uri' => $invoice_pdf->getFileUri(),
          'filemime' => $invoice_pdf->getMimeType(),
        ];
      }

      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = $params['title'];
      if ($params['message']['invoice_fid']) {
        $message['params']['files'][] = $invoice_file;
      } 
      $body_data = [
        '#theme' => 'invoice_email',
        '#orderdata' => $params['message']
      ];
      $message['body'][] = \Drupal::service('renderer')->render($body_data);
      break;
  }
}

The e-mail needs to be registered in your .module file:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'invoice' => [
      'template' => 'invoice-email',
      'variables' => ['orderdata' => []],
    ],
  ];
}

In your templates folder, add a file named invoice-email.html.twig. Add your markup here:

<p>Hello {{ orderdata['name'] }},</p>
<p>In attachment you can find your invoice for your purchase.</p>

By doing this, you'll be sending e-mails with nice attachments. Do not forget to configure your mailsystem for html e-mails as well.