1

I'm trying to do a nicely formatted email from a plugin I'm making. The standard way I've been doing simple emails is all entirely in the code, somewhat like this:

$notificationEmail = new EmailModel();
$notificationEmail -> toEmail  = $userEmail;
$notificationEmail -> subject  = "Subject here";
$notificationEmail -> body     = "Thanks $userName, you’re now registered on our website.";
$notificationEmail -> htmlBody = " ... MASSIVE COMPLICATED STUFF THATS FAR BETTER SUITED TO TWIG ... "
craft()->email->sendEmail($notificationEmail);

I've now got an email that is far better suited to being generated via a Twig template because I'm going to have to loop through relational fields and all sorts. I have no idea how and I don't seem to know what to Google to get what I'm after... Anyone got pointers to this sort of thing?

  • Guessing either $notificationEmail->htmlBody = craft()->templates->renderString($myComplicatedStuff); or $notificationEmail->htmlBody = craft()->templates->renderTemplate('/path/to/my/complicated/template'); is what you're looking for? – Brad Bell Oct 31 '17 at 17:15
  • Quite possibly the latter! How do I pass the User or other variables to that template though? – Matt Wilcox Oct 31 '17 at 17:23
  • 1
    Actually it's just render() for the latter and takes a 2nd $variables param. craftcms.com/classreference/services/… – Brad Bell Oct 31 '17 at 17:28
  • 1
    Let me now if that works for you and I'll add it as an answer. – Brad Bell Oct 31 '17 at 17:28
0

Thanks to Brad for providing the bulk of the answer. In more detail the line needing to be changed was this:

$notificationEmail -> htmlBody = craft()->templates->render('PLUGIN-FOLDER-NAME/TEMPLATE-NAME', ['theUser' => $user]);

I could then use {{ theUser }} (Which is a UserModel) in the TEMPLATE-NAME template to generate everything I needed.

So the full solution, to send an Email from a plugin, but using a Twig template to generate the HTML email content was:

$myEmail             = new EmailModel();
$myEmail -> toEmail  = $user->email;
$myEmail -> subject  = "Subject here";
$myEmail -> body     = "PLAIN TEXT CONTENT";
$myEmail -> htmlBody = craft()->templates->render('PLUGIN-FOLDER-NAME/TEMPLATE-NAME', ['theUser' => $user]);
craft()->email->sendEmail($myEmail);

Where $user was a variable containing a UserModel which I'd already got from previous code in the plugin I was writing.

https://craftcms.com/classreference/services/TemplatesService#render-detail for more detail (but for which I wish there were example code of how to use, and not just a dictionary).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.