Search Courses

Search Courses
Home / Blog
Easy way to send email using nodejs and express

Easy way to send email using nodejs and express

Posted on : 29,Dec 2015 3164

Send email from gmail account using express-mailer

Sending emails from node.js test servers where email server (smtp) is not congfigured is a challenge. One way to work around this challenge is using your own email account to send emails.With this apporach you can send notifications, auto alerts etc from your test website. The same method can be used while your website is hosted on free web servers like heroku, IBM Bluemix etc. This article talks about sending emails from node.js using a gmail account.

First thing first,

Assuming you already have a gmail account, we would want to keep the security less on your email account. This is done to allow the external website to access and send emails from your private account. If this step is not taken care of you may get error from gmail.


Please log in via your web browser and then try again. Learn more at https://support.google.com/mail... i8sm4869974obt.3 - gsmtp

To enable this option on gmail.

Login to gmail > Goto My Account > Sign-in & security > Connected apps & sites > Allow less secure apps: ON



There are so many packages available to send email from node.js. Package used here is express-mailer. You can add express-mailer in your package.json if your code is on some PaaS or if node.js server is running on local install express-mailer using

$ npm install express-mailer

Once express-mailer is installed, add below code to app.js. Express Mailer extends your express application.

var mailer = require('express-mailer');
mailer.extend(app, {
from: 'Any name you want to show in email',
host: 'smtp.gmail.com', // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
transportMethod: 'SMTP', // default is SMTP. Accepts anything that nodemailer accepts
auth: {
user: 'myemailid@gmail.com', // email id
pass: 'password' // password
}
});

Now for the content of email, i.e body of email can be rendered same way as you render a view for your website Mailer views use the same render process as Express. So whatever view engine you have same can be used to create the body of email. In this example view engine is jade.To set the view directory to project/views and view engine to jade you would write. If you have a working expressjs application, you can skip this step.

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

Go to view path and create a new jade name it email.jade, this will serve as an email template. For different purpose you can render different templates. i.e Thank you email, notification, alerts etc Good part of having template is you can make use of styling sheets. Below view shows a simple bootstrap template.

doctype html
head
title Website Name
link( rel='stylesheet',href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css')
body
nav.navbar.navbar-inverse.navbar-fixed-top
div.navbar-header
a.navbar-brand(href="http://your site")
img(src='https://some image' title='Website Name')
div.container
div.row
div.well
p
b
= body
div.form-group
div.col-sm-4
a(href="http://Website Name") Log In
div.col-sm-4
a(href="http://Website Name") Forgot Password?

In the above template the dynamic content or message will loaded while email is sent. Now how to send email. Use the below code snippet where you want to send email.

app.mailer.send('email', //view engine i.e template name
{
to: senders email id, // REQUIRED. This can be a comma delimited string just like a normal email to field.
subject: 'Password reset', // REQUIRED.
body: 'Your Password is set to xxxxx. Please log in back.,
otherProperty: 'Other Property' // All additional properties are also passed to the template as local variables.
}, function (err) {
if (err) {
// handle error
console.log(err);
res.send('There was an error sending the email '+err); //this will print error if email is not sent
return;
}
res.render('message', { // rendering the message screen after sending emil
name: name,
message: 'Password reset successfully'
});
});

If you do not need to call the send part at multiple places, create a function which can take all the arguments like template name, email ids, subject, body etc and just call the function wherever needed.

sendEmail(commenter_email,esubject,ebody,ebody2,etemplate,res);

function body goes like


  function sendEmail(id,subject,body,body2,template,res){
app.mailer.send(template, {
to: id, // REQUIRED. This can be a comma delimited string just like a normal email to field.
subject: subject, // REQUIRED.
body: body,
body2:body2,
otherProperty: 'Other Property' // All additional properties are also passed to the template as local variables.
}, function (err) {
if (err) {
res.send('Error'+err) ;
}
return ;
});
}

There are many more options and properties which can be set while sending emails.

template - REQUIRED - The name of the template to render
from - The e-mail address of the sender. All e-mail addresses can be plain sender@server.com or formatted Sender Name
to - Comma separated list or an array of recipients e-mail addresses that will appear on the To: field
cc - Comma separated list or an array of recipients e-mail addresses that will appear on the Cc: field
bcc - Comma separated list or an array of recipients e-mail addresses that will appear on the Bcc: field
replyTo - An e-mail address that will appear on the Reply-To: field
inReplyTo - The message-id this message is replying
references - Message-id list
subject - The subject of the e-mail
headers - An object of additional header fields {"X-Key-Name": "key value"} (NB! values are passed as is, you should do your own encoding to 7bit and folding if needed)
attachments - An array of attachment objects.
alternatives - An array of alternative text contents (in addition to text and html parts)
envelope - optional SMTP envelope, if auto generated envelope is not suitable
messageId - optional Message-Id value, random value will be generated if not set. Set to false to omit the Message-Id header
date - optional Date value, current UTC string will be used if not set
encoding - optional transfer encoding for the textual parts (defaults to "quoted-printable")
charset - optional output character set for the textual parts (defaults to "utf-8")
dsn - An object with methods success, failure and delay. If any of these are set to true, DSN will be used

If you want to check how email looks like before sending it , while in development you can render the email on screen using.

app.mailer.render instead of app.mailer.send

And that is it, hope it helps. Share your thoughts and comments.



Join the discussion

Improve the thread with your input and questions.
Hari Ramesh
Big Data and Analytics Architect at Abbvie Inc

Member Since : Feb, 2014

LIBERTYVILLE Illinois

LinkedIn Twitter

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable networ

Take course on


Interested in node.js? We will notify you when knowledge is shared.