HTMLField content sends Email with HTML Tags

Silverstripe Version: 4

Question: I have set the email body content to be captured from a HtmlEditorField through the CMS, but the email notification shows the HTML tags in the body too. How to fix this please?

//Controller Page
$From = 'test@gmail.com';
|---|---|---|
$To = $data['Email'];
$Subject = $this->EmailSubjectContent;
$email = Email::create();
$email->setFrom('test@gmail.com', 'Website Notification');
$email->setTo($To);
$email->setSubject($Subject);
$email->setHTMLTemplate('Email\\ShowcaseConfirmation');

$data['emailbody'] = $this->EmailBodyContent;
$email->setData($data);
$email->send();

//HTML Template SS

//CMS Field

First off, please don’t paste images of code. Your template code should have been pasted in as text. That makes it easier for people with vision impairments to help you and to benefit from any answers to this question as well as meaning people can copy/paste the code as needed to help you.

On to the actual question:
Because this template doesn’t have any concept of how the data was originally stored, it doesn’t know that it’s meant to be cast as html. It’s casting it as plain text (see “Text” in common casting types in the docs) by default because that’s safer.

You’ll need to tell the template explicitly either to treat this as raw text, or that it’s HTML content.

Resolving this using explicit template casting

To tell it to treat it as raw text, call the RAW() method on your $emailbody in the template. See commonly useful formatting methods in the docs for more info but it’s basically making this change in your template:

- <p>$emailbody</p>
+ <p>$emailbody.RAW</p>

Resolving this using default casting

To tell the template that this is explicitly HTML-safe content, you can wrap it in a DBHTMLText object in your PHP code. That would be this change:

- $data['emailbody'] = $this->EmailBodyContent;
+ $data['emailbody'] = DBField::create_field('HTMLText', $this->EmailBodyContent, 'emailbody');

This basically gives the value a default cast type, so it doesn’t get cast to Text, and therefore you don’t need to call RAW in your template.

1 Like