Question
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?
Solution
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(['<', '>'], ['<', '>'], $rendered->__toString()),
]);