Send email using nodejs and express in 5 simple steps

Send­ing auto­matic emails is a very com­mon task and doing so in nodejs is pretty straigt­for­ward as well. In this arti­cle, I will demon­strate a sim­ple exam­ple of send­ing emails using nodejs in 5 sim­ple steps.


This arti­cle is writ­ten around the fol­low­ing sce­nario in mind

  • You have an email account with an email provider like Google which you want to spec­ify as the ‘sender’. There is a sim­ple rea­son­ing behind doing so. Emails are sent from one server to another and in order to avoid land­ing your email in the recipient’s spam folder, you want to use a truster server as the sender of the email aka — Google’s mail servers. For the pur­pose of this arti­cle, we will assume this email address is [email protected].
  • You have a web page that has a con­tact form where a user enters some infor­ma­tion and clicks on sub­mit. Upon click­ing sub­mit your express server needs to cap­ture this data and send the request infor­ma­tion to another email address.

I assume that you have at least a basic under­stand­ing of nodejs and its rout­ing. If not, take a look at this dia­gram that visu­ally depicts how rout­ing takes place in expressjs.

You prob­a­bly also want to change some set­tings on the gmail account you want to use before proceeding.

Steps

There are just 5 steps to send­ing an email using nodejs

  • Install the node­mailer package.
  • Cre­ate a trans­port object using nodemailer.createTransport() and pass it your email credentials.
  • Pre­pare the mes­sage to be sent in the body.
  • Cre­ate an object with infor­ma­tion about the sender, email sub­ject, recip­i­ent and the body con­tent that we pre­pared earlier.
  • Send the email using — transporter.sendMail()

In the code snip­pets that fol­low, we will go through each of the above steps.


STEP 1: Install the node­mailer package.

npm install nodemailer

Once you are done with this arti­cle, you should prob­a­bly learn more about node­mailer library from here.
.
STEP 2: Cre­at­ing a trans­port object in your route handler.

var nodemailer = require('nodemailer');

var router = express.Router();
app.use('/sayHello', router);
router.post('/', handleSayHello); // handle the route at yourdomain.com/sayHello

function handleSayHello(req, res) {
    // Not the movie transporter!
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: '[email protected]', // Your email id
            pass: 'password' // Your password
        }
    });
    ...
    ...
    ...
}

STEP 3: Pre­pare some plain­text or HTML con­tent to be sent in the body. I am going to sim­ply use some text.

var text = 'Hello world from \n\n' + req.body.name;

STEP 4: Cre­ate a sim­ple JSON object with the nec­es­sary val­ues for send­ing the email.

var mailOptions = {
    from: '[email protected]>', // sender address
    to: '[email protected]', // list of receivers
    subject: 'Email Example', // Subject line
    text: text //, // plaintext body
    // html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
};

STEP 5: Your moment of glory! — Actu­ally send the email and han­dle the response.

transporter.sendMail(mailOptions, function(error, info){
    if(error){
        console.log(error);
        res.json({yo: 'error'});
    }else{
        console.log('Message sent: ' + info.response);
        res.json({yo: info.response});
    };
});

And thats pretty much all there is to it! It was quite sim­ple, wasn’nt it?


  • Eros Gar­cia Ponte

    Great tuto­r­ial. Who would imag­ine it was so simple.

  • Rafa Death

    I get Error: Invalid login with gmail 🙁

    • Enokela P. Acheme

      For this to work, you must allow less secure apps in your gmail settings

  • tuto­ri­al­hori­zon

    Last I remem­ber gmail had a per-day limit, around 500 for send­ing emails this way. Its either that or it does not allow you to send to more than 500 recipients.

    Using gmail would work for sim­ple use cases. But for pro­duc­tion sce­nar­ios, you prob­a­bly want to use some­thing like mailgun.com to send emails.

    Maybe I should do a quick writeup on that one too.

    • Joe

      That would be great!

  • tuto­ri­al­hori­zon

    I have just now posted a reply to Jodge for the same. You can check it out.

  • Cl Sah

    I have an error mes­sage i.e “Unable to send email: Error: Unsup­ported con­fig­u­ra­tion, down­grade Node­mailer to
    v0.7.1 to use it”

  • Luís Cunha

    I get this error when run­ning this

    Type­Er­ror: this.mailcomposer.setMessageOption is not a function

    at Nodemailer.setGeneralOptions (D:gitnodemailernode_modulesnodemailerlibnodemailer.js:228:23)

    at Nodemailer.generateMailObject (D:gitnodemailernode_modulesnodemailerlibnodemailer.js:184:10)

    at Nodemailer.sendMail (D:gitnodemailernode_modulesnodemailerlibnodemailer.js:172:10)

    at D:gitnodemailernode_modulesnodemailerlibnodemailer.js:69:20

    at Nodemailer.validateSettings (D:gitnodemailernode_modulesnodemailerlibnodemailer.js:161:5)

    at send­Mail (D:gitnodemailernode_modulesnodemailerlibnodemailer.js:63:12)

    at Transport.transport.sendMail (D:gitnodemailernode_modulesnodemailerlibnodemailer.js:40:9)

    at Object. (D:gitnodemailerapp.js:19:13)

    at Module._compile (module.js:399:26)

    at Object.Module._extensions..js (module.js:406:10)

  • jscon­estilo

    Gra­cias por la infor­ma­ción, muy útil

  • https://coolelectronicgifts.com/ Cool­elec­tron­icgifts

    Looks good!

  • Lucy

    I tried the same, but I keep get­ting POST http://localhost:8080/contact 404 (Not Found) error. Any­one know what could be reason?

  • Lucy

    I fol­low the same, but keep get­ting error POST http://localhost:8080/contact 404 (Not Found)

  • Mohit Mit­tal

    Awe­some tuto­r­ial. Worked like charm in the first go. Never expected from a mail tuto­r­ial to work in the first go !

  • http://erik.landvall.se/ Erik Land­vall

    this doesn’t send any emails, gmail does.. bet­ter head­line: how to send emails through gmail with nodejs and Express…