Sending HTML emails from Node.JS using MailGun

Skywalker picture Skywalker · Apr 21, 2016 · Viewed 8.4k times · Source

I send email notifications to my users from my app but currently I only send it as a text. I would like to send it HTML emails which are styled.

Currently I tried this:

var data = {
              from: 'my app',
              to: user.email,
              subject: 'Welcome',
              html: '<div style="width: 500px; height: 400px: background: #ebebeb; color: #ddd"><p>Hi  + "user.firstName" + \n ,this email is to inform you that has added their bio to the knowledge Base \n</p></div>'
           };

Compiling the above code does not work, it does not like the styles I have put in. I have created a separate HTML file within my local directory for each type of email I want send and I would like to be able to attach that html file to my email.

Something like this:

var data = {
              from: 'my app',
              to: user.email,
              subject: 'Welcome',
              html: welcomeToSiteEmail.html
           };

Is the above possible? Any help will be greatly appreciated.

Answer

duncanhall picture duncanhall · Apr 21, 2016

You can use mailgun-js together with mailcomposer to send HTML formatted emails.

The mailgun-js docs include an example:

var domain = 'mydomain.mailgun.org';
var mailgun = require('mailgun-js')({ apiKey: "YOUR API KEY", domain: domain });
var mailcomposer = require('mailcomposer');

var mail = mailcomposer({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Test email subject',
  body: 'Test email text',
  html: '<b> Test email text </b>'
});

mail.build(function(mailBuildError, message) {

    var dataToSend = {
        to: '[email protected]',
        message: message.toString('ascii')
    };

    mailgun.messages().sendMime(dataToSend, function (sendError, body) {
        if (sendError) {
            console.log(sendError);
            return;
        }
    });
});