0

I want to send an XML mail using Drupal's mailManager.

I have created a custom twig template in my module that will the the mail body.

Here's what my template looks like, my-module-xml-mail.html.twig:

<record>
  <name>{{ name }}</name>
  <phone>{{ phone }}</phone>
  <email>{{ email }}</email>
</record>

And my template definition:

function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module_xml_mail' => [
      'variables' => [
        'name' => NULL,
        'phone' => NULL,
        'email' => NULL,
      ]
    ]
  ];
}

And where I send the mail:

$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => $rendered,
]);

The problem is that when the mail is sent all the XML tags are stripped and only the values from the tags are sent.

How can I send the XML as plain text?

I thought about creating a my-module-xml-mail.xml.twig if that's possible, but when "kinting" the result from the renderer service it looks like renderer is not stripping any tags.

Do I need to send any headers to the mail, in order to send the XML as plain text?

0

I found a solution myself.

The problem is that Drupal's mail system converts HTML to plain text, and therefore strips all HTML tags.

A workaround to this is to replace all < and > characters with their unicode string and send the mail as text/plain.

I did like this:

$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => str_replace(['<', '>'], ['&#60;', '&#62;'], $rendered->__toString()),
]);
| improve this answer | |
  • Why not sending an HTML mail in the first place? – leymannx Oct 18 '19 at 13:15
  • That doesn't work either, MailFormatHelper::htmlToText() removes all the XML tags even though I'm sending it as an HTML mail. – user72672 Oct 18 '19 at 13:18
  • Is it actually sending as text/html though? – Kevin Oct 18 '19 at 13:25
  • @Kevin I don't understand your question. I send the mail as text/plain. – user72672 Oct 18 '19 at 13:28
  • I just convert the < and > characters, so they dont get stripped when creating the mail. – user72672 Oct 18 '19 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy