Render Twig template as XML 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:

&lt;record&gt;
  &lt;name&gt;{{ name }}&lt;/name&gt;
  &lt;phone&gt;{{ phone }}&lt;/phone&gt;
  &lt;email&gt;{{ email }}&lt;/email&gt;
&lt;/record&gt;


And my template definition:

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


And where I send the mail:

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

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

\Drupal::service('plugin.manager.mail')-&gt;mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' =&gt; $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?
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 &lt; and &gt; characters with their unicode string and send the mail as text/plain.

I did like this:

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

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

\Drupal::service('plugin.manager.mail')-&gt;mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' =&gt; str_replace(['&lt;', '&gt;'], ['&amp;#60;', '&amp;#62;'], $rendered-&gt;__toString()),
]);