“View in Browser” link is a common feature of email campaign systems like MailChimp. It’s a really nice idea – when you code your shiny CSS-heavy emails you want to have a fallback for malfunctioning email clients.
But what if you want to implement this feature on your own? Read on to learn how to send emails in Node.js with “View in Browser” link and inlined CSS.
We will use Nodemailer for email transport and node-email-templates for rendering templates and inlining CSS styles. The code was tested under Node.js 5.7.1.
Let’s start with implementing just the email transport. Nodemailer has “callback-based” API while I prefer to use generator based flow control offered by co. That’s why we need Q to convert “callback-based” API to “promise-based” API which can be used by co.
We are using the default SMTP transport here. You can use MailCatcher for development, to quickly have something running. For production I recommend checking out other transports like nodemailer-mandrill-transport.
The next step is to use node-email-templates. I decided to use Jade for templating and Sass as CSS preprocessor:
p This is some content for you
Inside context object we pass values for interpolation in the template. Please also note that Sass styles are automatically compiled to CSS and inlined for us!
How are we going to implement “View in Browser” functionality? My approach is simple – store generated email content in MongoDB, assign it some long random identifier and serve this content via a web application.
Let’s start by creating a function which connects to MongoDB and inserts email content identified by the token (UUID). I’m hardcoding address of local MongoDB instance for the purpose of this example.
Please note that we are executing rawSend and saveContentconcurrently, because we are passing array of promises to yield.
As the next step, let’s extract the code related to database communication to a separate module – db.js. We need find function which shares some code with save function so we extract to avoid duplicating the code.