How to Send Email in Node.js Using Nodemailer
To send email in
Node.js, use the nodemailer library which simplifies SMTP email sending. Install it with npm install nodemailer, create a transporter with your email service details, then use transporter.sendMail() to send your message.Syntax
Sending email in Node.js with Nodemailer involves these steps:
- Import nodemailer: Load the library to use its functions.
- Create a transporter: Set up your email service credentials (SMTP server, port, user, password).
- Define mail options: Specify sender, receiver, subject, and message body.
- Send the email: Call
sendMail()on the transporter with mail options.
javascript
import nodemailer from 'nodemailer'; const transporter = nodemailer.createTransport({ host: 'smtp.example.com', port: 587, secure: false, // true for 465, false for other ports auth: { user: 'your_email@example.com', pass: 'your_password' } }); const mailOptions = { from: 'your_email@example.com', to: 'recipient@example.com', subject: 'Subject here', text: 'Email body text' }; transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message sent: %s', info.messageId); });
Example
This example shows how to send a simple email using Gmail's SMTP server with Nodemailer in Node.js. It demonstrates creating a transporter, setting mail options, and sending the email with async/await.
javascript
import nodemailer from 'nodemailer'; async function sendEmail() { // Create transporter using Gmail SMTP const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your_email@gmail.com', pass: 'your_app_password' } }); // Define email options const mailOptions = { from: 'your_email@gmail.com', to: 'friend@example.com', subject: 'Hello from Node.js', text: 'This is a test email sent using Nodemailer!' }; try { const info = await transporter.sendMail(mailOptions); console.log('Email sent: ' + info.messageId); } catch (error) { console.error('Error sending email:', error); } } sendEmail();
Output
Email sent: <unique-message-id>
Common Pitfalls
Common mistakes when sending email in Node.js include:
- Using incorrect SMTP settings or ports.
- Not enabling less secure app access or using app passwords for Gmail.
- Forgetting to handle asynchronous code properly, causing the program to exit before sending completes.
- Not catching errors from
sendMail(), which hides issues.
Always check your credentials and use async/await or callbacks correctly.
javascript
/* Wrong: Missing async/await or callback, program may exit before sending */ import nodemailer from 'nodemailer'; const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'email@gmail.com', pass: 'password' } }); const mailOptions = { from: 'email@gmail.com', to: 'to@example.com', subject: 'Hi', text: 'Test' }; transporter.sendMail(mailOptions); /* Right: Use async/await to wait for sending to finish */ async function send() { try { const info = await transporter.sendMail(mailOptions); console.log('Sent:', info.messageId); } catch (e) { console.error('Error:', e); } } send();
Quick Reference
Tips for sending email in Node.js with Nodemailer:
- Install Nodemailer with
npm install nodemailer. - Use
createTransport()with correct SMTP or service settings. - Use async/await or callbacks to handle sending asynchronously.
- For Gmail, use app passwords and enable access for less secure apps if needed.
- Always handle errors to debug sending issues.
Key Takeaways
Use the Nodemailer library to send emails easily in Node.js.
Create a transporter with your SMTP or email service credentials.
Always handle asynchronous sending with async/await or callbacks.
Check and configure your email service settings correctly.
Handle errors to catch and fix sending problems.