Sending form to mail from custom module fails without error
Question
I've created a module with a form and a block.
When I push the subscribe button, the submitForm function is executed.
The successmessage is shown, but no e-mail is send ...
There are no errors reported in the recent logmessages or in on the server in the folder /logs.
public function submitForm(array &$form, FormStateInterface $form_state)
{
/**
* @var MailManager $mailer
*/
$mailer = \Drupal::service('plugin.manager.mail');
$email = $form_state->getValue('email');
$params['context']['subject'] = "Subscribe newsletter";
$params['context']['message'] = 'Someone subscribed: ' . $email;
$params['email'] = $email;
try {
$response = $mailer->mail('my_module', 'subscribe', 'to@email.com', 'nl', $params);
if ($response) {
$this->messenger()->addStatus($this->t('You are successfully subscribed to our newsletter with your e-mail: @email', ['@email' => $email]));
} else {
$this->messenger()->addStatus($this->t('There was an error.'));
}
} catch (MailHandlerException $e) {
\Drupal::logger('mailinglist_send_mail_error')->notice('<pre><code>' . print_r($e, true) . '</code></pre>');
}
}
Solution
Did you implement hook_mail in your module? – Alfred Armstrong
where to place the hook_mail function? – Lance
Goes in the .module file. Ex: my_module.module
/*
* Implements hook_mail().
*/
function my_module_mail($key, &$message, $params) {
switch($key) {
case 'my_module':
$options = [
'langcode' => $message['langcode'],
];
$message['subject'] = t('@title', ['@title' => $params['context']['subject']], $options);
$message['body'][] = t('@body', ['@body' => $params['context']['message']], $options);
break;
}
}
Flush all caches so hook gets picked up.
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange