Sending Emails with Node.js using Nodemailer
Sanket Bodake 🇮🇳
Posted on December 20, 2023
What is Nodemailer ?
Nodemailer is a module for Node.js that simplifies the process of sending emails from a Node.js application. It provides an easy-to-use API for composing and sending emails using various email services and transport methods. With Nodemailer, you can send plain text emails, HTML emails, and even attachments.
Install Nodemailer
Use the following command to install nodemailer :
npm install nodemailer
Configure Nodemailer
Below is an example of configuring Nodemailer with Gmail using the SMTP (Simple Mail Transfer Protocol).
const nodemailer = require('nodemailer');
// Create a transporter object using Gmail SMTP
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-email-password'
}
});
// Additional configuration options
const mailOptions = {
//...
};
// Send email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error:', error);
} else {
console.log('Email sent:', info.response);
}
});
Additional Configuration Options
You can customise the email further by adding options to the mailOptions object.
const mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@example.com',
subject: 'Test Email',
text: 'This is a test email sent from Node.js using nodemailer.',
html: '<p>This is a <b>test</b> email sent from Node.js using nodemailer.</p>',
attachments: [
{
filename: 'attachment.txt',
content: 'Attachment content'
}
]
};
These options allow you to specify the sender, recipient, subject, email body (both plain text and HTML), and even attachments.
Conclusion
To wrap it up, Nodemailer is a handy tool in Node.js for sending emails easily. Whether you're just sending simple messages or dealing with more complex email tasks, Nodemailer is flexible enough to handle it. As you use Nodemailer, keep an eye on any updates and best practices to keep your email communication smooth and trouble-free. Enjoy coding!
So, If you find this helpful please like and share it with everyone.
Sharing is Caring!
Thank you :)
Posted on December 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.