0

I am using hook_mail_alter to modify the email that the user gets when an administrator creates an account. What I am trying to do is create a link in the email body, the link gets created but it adds a [1] to the link text and after the email text is done. There is the [1] again with the actual link. Is there anyway to actually have the link created in the text instead of having it render at the end? Here is my code:

function my_module_mail_alter(&$message) {
if ($message['id'] = 'user_register_admin_created') {

    $url = Url::fromUri('https://www.google.com');
    $external_link = \Drupal::l(t('Google'), $url);
    $message['body'][] = t("Go to: ");
    $message['body'][] = $external_link;
}
}

1 Answer 1

1

That happens because the class normally handling the email sending (PhpMail) uses the following code, in PhpMail::format().

  // Convert any HTML to plain-text.
  $message['body'] = MailFormatHelper::htmlToText($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = MailFormatHelper::wrapMail($message['body']);

In particular, this is the code handling the links. (See the comment before the code.)

  // Replace inline <a> tags with the text of link and a footnote.
  // 'See <a href="https://www.drupal.org">the Drupal site</a>' becomes
  // 'See the Drupal site [1]' with the URL included as a footnote.
  static::htmlToMailUrls(NULL, TRUE);
  $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  $urls = static::htmlToMailUrls();

To send HTML emails, you need a different class implementing MailInterface. The Swift Mailer module implements it, for example, and allows to send HTML emails; it also allows to select in which way to send a message (server SMTP, MTA agent, mail() function).
The Mail System module provide a UI that allows to select the mail plugin used to send emails, so you don't need to mess with the configuration to do it.

screenshot

3
  • 2
    Nope, the mail system module doesn't allow to send HTML mails, it just provided a UI to configure the used mail plugin so that one that supports HTML, like Swiftmailer, can be selected.
    – Berdir
    Nov 24, 2016 at 20:38
  • I didn't remember I installed two modules. I will edit my answer.
    – apaderno
    Nov 25, 2016 at 3:56
  • Alright so I did install both modules, the only extra step not mentioned here, but I understand why since it would be a separate thread is that you need to install the php swiftmail library via composer. Just mentioning but the steps you wrote are correct. Thank you! Nov 29, 2016 at 14:18

Your Answer

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

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