I am trying to use the MailManager class in Drupal 8 to send HTML mail, I got it working but it isn’t parsing the HTML markup. Something is wrong with the headers of the email I think!
What I have is a custom module called ‘Custom_forward’ that contains a form and the mailmanager:mail method is located in the submitForm. As you can see here:
// Email body $ header = $ sender . ' thought you would like to see this page from the website.'; $ personal_message = $ form_state->getValues()['message_body']; $ entity_url_value = '<a href="' . $ entity_url->toString() . '">Go to article</a>'; $ message = $ header . '<br>' . $ personal_message . '<br>' . $ entity_url_value; // Email $ langcode = 'en'; $ mailManager = \Drupal::service('plugin.manager.mail'); $ to = $ form_state->getValues()['recipient']; $ params['title'] = 'Forward'; $ params['message'] = $ message; $ result = $ mailManager->mail('custom_forward', 'forward', $ to, $ langcode, $ params, NULL, true); if ($ result['result'] !== true) { drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error'); \Drupal::logger('mail-log')->error($ message); } else { drupal_set_message(t('Your message has been sent.')); }
According to Drupal you also need the hook_mail method in mytheme.theme to be able to send message, you can see this method here:
function custom_forward_mail($ key, &$ message, $ params) { $ message['body'] = []; $ message['subject'] = []; $ message['headers'] = array( 'content-type' => 'text/html', 'charset' => 'UTF-8', 'format' => 'flowed', 'delsp' => 'yes', 'from' => \Drupal::config('system.site')->get('mail') ); switch ($ key) { case 'forward': $ message['subject'] = $ params['title']; $ message['body'][] = '<html><body>' . $ params['message'] . '</body></html>'; break; } }
As you can see I am setting content type to be text/html which should tell the mail system to parse the content as an HTML mail, But this is not working for some reason,
This is a testing email, all the html markup is not shown but also not working!
Bassem thought you would like to see this page from the website. personal message Go to article [1] [1] http://myhost/node/81