Tuesday, March 22, 2016

Send email in Drupal 8

Send email in Drupal 8

<?php
/**
* Implements hook_mail().
*/
function mymodule_mail($key, &$message, $params) {
  $options = [
    'langcode' => $message['langcode'],
  ];

  switch ($key) {
    case 'order_confirmation':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('test: @subject', [
        '@subject' => $params['subject'],
      ], $options);
      $message['body'][] = $params['body'];
      break;
  }
}

function mymodule_sendOrderConfirmation($toEmail, $params) {
  \Drupal::service('plugin.manager.mail')->mail(
    'mymodule',
    'order_confirmation',
    $toEmail,
    \Drupal::languageManager()->getDefaultLanguage()->getId(),
    $params,
    NULL, // Optional email address to be used to answer.
    TRUE
  );
}

mymodule_sendOrderConfirmation('test@example.com', [
  'subject' => 'test subject',
  'body' => 'test body',
]);
?>

No comments: