How to Send Email in NodeJs using nodemailer?


How to Send Email in NodeJs using nodemailer




Sending emails is a common task for many web applications, and Node.js makes it easy to do so with its built-in libraries and modules. In this blog post, we will explore how to send emails in Node.js using the popular Nodemailer library.

First, we need to install the Nodemailer library by running the following command in the terminal:

npm install nodemailer

Once the library is installed, we can import it into our Node.js application using the following code:

const nodemailer = require('nodemailer');

Next, we need to create a transporter object, which will be used to send the email. This can be done using the following code:

let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your-email-address@gmail.com', pass: 'your-email-password' } });

In this example, we are using the Gmail service to send the email, but Nodemailer supports many other services such as Yahoo, Hotmail and more.

Once the transporter object is created, we can then use it to send an email. We do this by creating a mail object, which contains the details of the email such as the recipient, subject, and message body. Here is an example of how to create a mail object:

let mailOptions = { from: 'your-email-address@gmail.com', to: 'recipient-email-address@example.com', subject: 'Hello, World!', text: 'This is a test email sent from Node.js.' };

Finally, we use the transporter object to send the email by calling the sendMail() function and passing in the mail object as an argument. Here is an example of how to send the email:

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

And that's it! With just a few lines of code, we were able to send an email using Node.js and the Nodemailer library. You can also customize the mail object to include attachments, HTML content, and more.

It's worth noting that, depending on the service you're using, there may be additional security measures that need to be taken, such as allowing less secure apps to access your account. And also using an external service like SendGrid or Mailgun could be more secure and reliable for production use.

Sending emails is a fundamental feature for many web applications, and Node.js makes it easy to do so with its built-in libraries and modules like Nodemailer. With just a few lines of code, you can send emails and customize them to suit your needs.

Comments

Popular posts from this blog

Angular Best Practices and Coding Standards: A Guide for Developers

Top 7 ways to use Interceptors in Angular

How to SSH AWS EC2 instance?