I like to use a node as mail body in Drupal 8. I have written a simple module which works fine except for output formatting:
function foo_notification_node_insert($node) {
$type = $node->getType();
if ($type === 'foo') {
$to = '[email protected]';
// passed to hook_mail
$params = array(
"node" => $node
);
\Drupal::service('plugin.manager.mail')->mail(
'foo_notification',
'notice',
$to,
'de',
$params
);
}
function foo_notification_mail($key, &$message, $params) {
$node = $params["node"];
// subject
$message['subject'] = "New node: " . $node->getTitle();
// render body
$view_builder = \Drupal::entityTypeManager()->getViewBuilder($node->getEntityTypeId());
$view = $view_builder->view($node, 'default', 'de');
$message['body'][] = render($view);
}
If I understood correct $view_builder->view($node, 'default', 'de');
returns a render array. This one is rendered to HTML by render($view);
. Drupal mail service converts HTML in message body to plain text. And that looks ugly.
Rendered mail body looks like:
---------------- My node title -------------------------------------
first field label
first field value
second field label
second field value
third field label
third field value contains a longer text which break
at some point and is continued like this. Just for demonstration a
few more lines.
This ist how it looks like if it contains a line break. It's ugly.
The node has multiple fields and I like to use same view for representation on page (HTML) and in mail (plain text) - especially the order and formatting of node fields.
So what's the correct solution?