Using dynamic HTML templates in Meteor emails

meteor

Solution

Yes this is possible, here I provide a client-side solution to this common problem.

First you should define a simple template that will serve as your email html body :

<template name="shareEmailContent">
  <p>{{message}}</p>
  <a href="{{url}}">{{title}}</a>
</template>

Then you can use Email.send (see Email.send at docs.meteor.com, you'll need some proper configuration such as adding the email Smart Package and setting `MAIL_URL`) to email the result of the template rendering. Email.send only works on the server, so you must define a server method callable from the client.

Server side :

Meteor.methods({
  sendShareEmail:function(options){
    // you should probably validate options using check before actually
    // sending email
    check(options,{
      from:String,
      // etc...
    });
    Email.send(options);
  }
});

Client side :

var dataContext={
  message:"You must see this, it's amazing !",
  url:"http://myapp.com/content/amazingstuff",
  title:"Amazing stuff, click me !"
};
var html=Blaze.toHTMLWithData(Template.shareEmailContent,dataContext);
var options={
  from:"sender@domain.com",
  to:"receiver@domain.com",
  subject:"I want to share this with you !",
  html:html
  })
};
Meteor.call("sendShareEmail",options);

As mentioned in the comments, you can also decide to render email templates on the server. Server-side rendering is not yet supported but you can still accomplish it using a third party templating package.

EDIT 06/09/2014 : updated to use the latest `Blaze` API as of Meteor 0.9.1

Problem

Is there a way to render a Meteor template as the HTML body of an email? For example if I want to show collection data or generate dynamic links inside that email.

Original source