Question

I created a module to send emails, but I don't now how to send emails.

Was it helpful?

Solution

Implement hook_mail in your custom MODULENAME.module file similar to the following

function MODULENAME_mail($key, &$message, $params) {
 $options = array(
   'langcode' => $message['langcode'],
 );
 switch ($key) {
   case 'general_mail':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('General mail: @subject', ['@subject' => $params['subject']], $options);
     $message['body'][] = $params['message'];
     break;
 }
}

And than to send email anywhere in your code using something like this

$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'MODULENAME';
$key = 'general_mail';
$to = "mail@mail.com";
$params['message'] = "This is the message";
$params['subject'] = "Mail subject";
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] !== true) {
  drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
}
else {
  drupal_set_message(t('Your message has been sent.'));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top