1

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', '[email protected]', '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>');
        }

    }
7
  • 1
    While logged out, if you go to /user/password and try to reset your password, do you get an e-mail?
    – No Sssweat
    Oct 9, 2020 at 8:36
  • Mustn't it be just $params['subject'] and $params['message'] without 'context'? And [email protected] be replaced with the $email value?
    – leymannx
    Oct 9, 2020 at 8:41
  • 1
    @NoSssweat that is not working indeed ...
    – Lance
    Oct 9, 2020 at 8:43
  • 1
    Did you implement hook_mail in your module? Oct 9, 2020 at 8:53
  • 2
    The SPF record was not correct. Due to this it was marked as spam. cPanel Track Delivery. That is ok, it is now received, but the mail is empty ... even without the context, it is still empty ...
    – Lance
    Oct 9, 2020 at 9:13

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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