How to send Email with node js for free
fawazsullia
Posted on May 31, 2021
If you are building a project that involves customer interactions, then probably at some point you would have to send them an email as well.
For example, on successful form submits, you need to send a confirmation email. Or on every purchase, a receipt or order details.
You could hook up some of the existing apis like send in blue, mail chimp etc, but you can do it for free in nodejs itself.
Node Mailer is a nodejs module, that makes it easy to send emails.
Here's how you do it;
-> First, install Node Mailer
npm install nodemailer
-> Then require('nodemailer')
-> Create a transporter
Transporter is the object that is able to send the email. It contains data about the connection.
I'm using gmail to send emails and this is how the transporter looks for me:
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: myemail@gmail.com,
pass: password
}
});
-> We also need an object containing the message to be sent
const mailOptions = {
from: 'The Idea project',
to: toAddress,
subject: 'My first Email!!!',
text: "This is my first email. I am so excited!"
};
You can send html emails with html key instead of text.
-> Next, to actually send the email, use
transporter.sendMail(mailOptions, callback)
The call back takes error and info arguments and is executed once the sending process is complete. You can use this to log errors if any.
You can customise the emails you send, where you send from and how you send it anyway you want. Read the docs here.
The complete code should look like this,
![Full code nodemailer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i116of2cgdf0d7eljgtb.png)
Posted on May 31, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.