Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
204 lines (159 sloc) 4.84 KB

Title: Sending e-mails with Node and NodeMailer Author: Dumitru Glavan Date: Mon Jun 18 2012 18:49:38 GMT+0200 (CEST) Node: v0.6.0

Sending e-mails with NodeJS is almost a breeze. Almost. First, you have to plug-in the NodeMailer module than set up a transport type, load the templates, add attachments and finally send...

The first thing you tend to do is to create a wrapper class to manage all this tasks. So, I wrapped it in an Eamiler class to centralize the mail sending in my app.

# /lib/

emailer = require("nodemailer")
fs      = require("fs")
_       = require("underscore")

class Emailer

  options: {}

  data: {}

  # Define attachments here
  attachments: [
    fileName: "logo.png"
    filePath: "./public/images/email/logo.png"
    cid: "logo@myapp"

  constructor: (@options, @data)->

  send: (callback)->
    html = @getHtml(@options.template, @data)
    attachments = @getAttachments(html)
    messageData =
      to: "'#{} #{}' <#{}>"
      from: "''"
      subject: @options.subject
      html: html
      generateTextFromHTML: true
      attachments: attachments
    transport = @getTransport()
    transport.sendMail messageData, callback

  getTransport: ()->
    emailer.createTransport "SMTP",
      service: "Gmail"
        user: ""
        pass: "secretpass"

  getHtml: (templateName, data)->
    templatePath = "./views/emails/#{templateName}.html"
    templateContent = fs.readFileSync(templatePath, encoding="utf8")
    _.template templateContent, data, {interpolate: /\{\{(.+?)\}\}/g}

  getAttachments: (html)->
    attachments = []
    for attachment in @attachments
      attachments.push(attachment) if"cid:#{attachment.cid}") > -1

exports = module.exports = Emailer

In a standard ExpressJS project structure you'll store this file in /lib/ You'll need to have the email templates stored in /views/emails/ as HTML files and the attachments in /public/images/email/.

A potential email view will look like this:

<!-- invite.html -->
  <title>Invite from Myapp</title>
    Hi {{name}} {{surname}},
    Myapp would like you to join it's network on <a href=""></a>.
    <br />
    Please follow the link bellow to register:
    <a href="{{id}}">{{id}}</a>
    Thank you,
    <br />
    Myapp Team
    <a href=""><img src="cid:logo@myapp" /></a>

UnderscoreJS template will take care about your variables in the template and the getAttachments() function will automatically attache the files you need by the cid from the template.

To use the class in your code you have to instantiate a new Emailer object with the desired options, the template data and send the email:

options =
    email: ""
    name: "Rick"
    surname: "Roll"
    subject: "Invite from Myapp"
    template: "invite"

data =
  name: "Rick"
  surname "Roll"
  id: "3434_invite_id"

Emailer = require "../lib/emailer"
emailer = new Emailer options, data
emailer.send (err, result)->
  if err
    console.log err

Using a MongooseJS: model for the invites you would have something like this:

InviteSchema = new Schema
    type: String
    type: String
    type: String
    type: String
    enum: ["pending", "accepted"]
    default: "pending"
    type: Number
    default: 0
    type: Date

InviteSchema.methods.send = ()->
  options =
      email: @email
      name: @name
      surname: @surname
    subject: "Invite from Myapp"
    template: "invite"
  Emailer = require "../lib/emailer"
  emailer = new Emailer options, @
  emailer.send (err, result)->
    if err
      console.log err

Invite = mongoose.model("Invite", InviteSchema)
exports = module.exports = Invite

And you'll call it from an ExpressJS router:

Invite = require('../models/invite')

module.exports = (app)-> '/invites', (req, res)->
    data = req.body
    invite = new Invite data ()->
    res.writeHead(303, {'Location': "/invites"})

  app.get '/invites', (req, res)->
    Invite.find().desc("created_at").run (err, invites)->
      res.render 'invites/invites', {title: "Invites", invites: invites}

That's all about it.

Your feedback is highly appreciated. Thanks.