Learn to Code via Tutorials on Repl.it!

← Back to all posts
Send Emails with Nodemailer!
h
Squirrel777 (90)

Welcome!

Today you will learn how to send emails using nodemailer! Now all you need is a new google account. You will see why!

Getting started and authorizing!

Lets get started by installing nodemailer!

var nodemailer = require('nodemailer');

Ok we got that done! Now, here comes the long part! We will need to authorize ourselves to send emails!
So, you will put the following code:

var transporter = nodemailer.createTransport({
  service: 'gmail',
  port: 587,
  secure: true,
  auth: {
    user: 'yourEmail',
    pass: 'yourPassword'
  }
});

And run the repl! Done! Right? No, you will get an error! To fix this, go here to enable less secure apps! Ok, hopefully you wont get any errors. But just one more thing! You need to keep your gmail and password private! (Unless you have a private repl) To do this, we will create a .env file! So go do that, and enter the following into the .env file:

EMAIL="[email protected]"
PASSWORD="yourPassword"

And put this in the index.js file:

var myEmail = process.env.EMAIL;
var myPassword = process.env.PASSWORD;

But. I think that is how I got hacked! So I would highly recommend creating and using an alternative account! Ok, now lets update the authorization!

var myEmail = process.env.EMAIL;
var myPassword = process.env.PASSWORD;
var transporter = nodemailer.createTransport({
  service: 'gmail',
  port: 587,
  secure: true,
  auth: {
    user: myEmail,
    pass: myPassword
  }
});

And that should work! Run the repl to see if you dont have errors, and continue reading this tutorial.

Sending the Email!

Now lets get to the part where we send the email. To do this, put the following code:

var mailOptions = {
  from: myEmail,
  to: myEmail, /*Replace this with '[email protected]' to send it to a friend! But for now we will be sending it to ourselves to see if this works!*/
  subject: 'Sending an email with nodemailer!',
  text: 'Hello!'
};

And there we go, now all we need is to add some code to send the email! Enter the following code:

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log('Oof!' + error); //raise an error
  } else {
    console.log('Email sent Successfuly!'); //Tell us if it went successful!
  }
});

Conclusion

So now you have sent an email using nodemailer! Let me know if you experience any errors or if you have questions! Thank you!