Email - set htmltemplate from a HTMLTextField rather than a SS file


#1

SS4.2

**Is it there a way to set the html template of Email to a html string rather than a SS file? **

This way, cms admin can edit the email template easily.


#2

I don’t think there’s a straightforward way, but it should be possible.
The Email class extends ViewableData, and uses the renderWith() method to create the email body. That uses an SSViewer instance for the template file.

In theory, you can create your own email class, and override the $renderWith() method. In there, instead of just passing a template name to get the SSViewer instance, you could create one with the SSViewer::fromString() method and carry on with the rest of the process as it currently runs. You’d probably need to add some extra functionality to allow you to actually set the HTML content as well (something like a setHTMLTemplateCode() or such-like)


#3

I’m using the stripped down snippet of code below to send Emails that are stored in a data table, so that my Project Admins can edit the emails through the CMS without me. It’s not perfect because the email body field (ie EmailTemplate below) is a Text data type, so all of the HTML and CSS code displays in the editor. Fortunately, I work closely with the Project Admins so this is acceptable.

<?php

use SilverStripe\Control\Email\Email;
use SilverStripe\View\SSViewer;
use SilverStripe\View\ArrayData;


class CustomMemberImportController extends Controller {
    public function sendInstructionalEmail($member, $password) {
        // call function that runs DB query
        $emailRecord = $this->getEmailRecord();

        $viewer = SSViewer::fromString($emailRecord->EmailTemplate);

        $html = $viewer->process(ArrayData::create([
            'Member'            => $member,
            'Password'          => $password,
        ]));

        $email = new Email();
        $email
            ->setTo($member->Email)
            ->setSubject($emailRecord->EmailSubject)
            ->setBody($html);
        $email->send();
    }
}

#4

thanks for the tips.

will try next time