1

I'm trying to send messages using Drupal 8's Mail API, but the messages always have an empty subject and body. Do you see anything wrong with the code?

In my module file:

function mymodule_mail($key, &$message, $params) {
    $options = array(
        'langcode' => 'en'
    );

    switch ($key) {
      case 'contact':
        $from = \Drupal::config('system.site')->get('mail');  //I'm not sure this is actually doing anything.
        $message['subject'] = 'Inquiry from Web Site';
        $message['body'][] = 'TEST BODY';
        break;
}

And within the submit method of my form:

 $langcode = 'en';
 $to = 'my@email.com';

 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = 'mymodule';
 $key = 'contact';

 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

I am getting the messages - and they are coming from the right email address (which may just be the default). But the subject and body are empty and I can't figure out why. Any suggestions would be appreciated!

1

Ok, I found the problem. You're gonna laugh!

My code for hook_mail was within the code block for the function above it! D'oh! All good now. Sorry for the false alarm.

1
  • hello I am facing the same problem, can you please elaborate the things you did to fix it or steps you followed. Thanks.
    – echo
    Nov 24 '16 at 12:10

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