Email communication is an essential part of modern web applications, whether for user registration, password resets, or transactional notifications. In this guide, we’ll explore how to send emails in Node.js using Nodemailer and popular email services like Gmail, SMTP, and SendGrid.
Setting Up Nodemailer
Nodemailer is the most popular package for sending emails in Node.js. Install it using npm
:
npm install nodemailer
Then, import and configure it in your Node.js script:
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail', // Can be changed to other services
auth: {
user: '[email protected]',
pass: 'your-email-password'
}
});
Note: If using Gmail, enable Less Secure Apps or set up an App Password.
Sending an Email
After configuring the transporter, send an email using:
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Test Email from Node.js',
text: 'Hello! This is a test email sent from Node.js using Nodemailer.'
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending email:', error);
} else {
console.log('Email sent:', info.response);
}
});
Using a Custom SMTP Server
If you’re using a custom SMTP server, update your transporter configuration:
const transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587, // or 465 for SSL
secure: false, // Set to true for port 465
auth: {
user: 'your-smtp-username',
pass: 'your-smtp-password'
}
});
Sending HTML Emails with Attachments
You can send HTML-formatted emails and include attachments:
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'HTML Email with Attachment',
html: '<h1>Welcome!</h1><p>This is a test email with <b>HTML</b> formatting.</p>',
attachments: [
{
filename: 'test.txt',
path: './test.txt'
}
]
};
Using SendGrid for Scalable Email Sending
For better scalability, you can use SendGrid. First, install the package:
npm install @sendgrid/mail
Then, configure and send an email:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('YOUR_SENDGRID_API_KEY');
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'SendGrid Email from Node.js',
text: 'Hello from SendGrid!',
html: '<strong>Hello from SendGrid!</strong>'
};
sgMail.send(msg)
.then(() => console.log('Email sent successfully'))
.catch(error => console.error('Error sending email:', error));
Conclusion
Sending emails in Node.js is a breeze with Nodemailer and awesome services like SendGrid! Whether you're after a quick setup or something that can grow with your needs, these options make it super easy to add email features to your app. Happy coding!Happy coding! 🚀
Hope you find this helpful!!
Sending Emails in Node.js