-6

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

1

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.'));
}
| improve this answer | |
  • thanks for your help , page show me "your message has been send" but when i check my email i don't find anything – john Feb 25 '19 at 13:35
  • Perhaps it has to do with the deleverability of your server or email or domain in general and it's a separate issue. Is your server in Gerald able to send email to this address ? – GiorgosK Feb 25 '19 at 13:58

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