I have been fiddling with sending a mail in my custom module in Drupal 8. The mail gets sent but the subject and body are empty. It has been an issue for days and I can't get it to work. The code and var_dump are below. I just can't find the issue. Maybe someone can!
Code in hook_mail
:
<?php
/**
* Implements hook_mail().
*/
function document_mail($key, $message, $params)
{
$options = array(
'langcode' => $message['langcode'],
);
switch ($key) {
case 'send_file':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('@title', array('@title' => $params['mail_title']), $options);
$message['body'][] = $params['message'];
break;
}
}
Code to send mail:
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'document';
$key = 'send_file';
$to = 'info@example.com';
$params['mail_title'] = 'a title';
$params['message'] = 'a message';
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, null, $send);
var_dump($result);
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.'));
}
var_dump of result from $result of mailManager
array(12) {
["id"]=> string(18) "document_send_file"
["module"]=> string(8) "document"
["key"]=> string(9) "send_file"
["to"]=> string(24) "info@example.com,"
["from"]=> string(22) "info@example.com"
["reply-to"]=> NULL
["langcode"]=> string(2) "en"
["params"]=> array(2)
{
["mail_title"]=> string(7) "a title"
["message"]=> string(9) "a message"
}
["send"]=> bool(true)
["subject"]=> object(Drupal\Core\StringTranslation\TranslatableMarkup)#410 (5)
{
["string":protected]=> string(6) "@title"
["translatedMarkup":protected]=> NULL
["options":protected]=> array(1)
{
["langcode"]=> string(2) "en"
}
["stringTranslation":protected]=> NULL
["arguments":protected]=> array(1)
{
["@title"]=> string(7) "a title"
}
}
["body"]=> array(1)
{
[0]=> string(9) "a message"
}
["headers"]=> array(7)
{
["MIME-Version"]=> string(3) "1.0"
["Content-Type"]=> string(51) "text/plain; charset=UTF-8; format=flowed; delsp=yes"
["Content-Transfer-Encoding"]=> string(4) "8Bit"
["X-Mailer"]=> string(6) "Drupal"
["Return-Path"]=> string(22) "info@example.com"
["Sender"]=> string(22) "info@example.com"
["From"]=> string(44) "a string"
}
["result"]=> bool(true)
}