
Email in NodeJs
Sending emails in Node.js is commonly done using the popular package Nodemailer. It's reliable and works with services like Gmail, Outlook, or any SMTP server.
✅ Step-by-Step: Sending Email with Node.js + Nodemailer
1. Install Nodemailer
npm install nodemailer
2. Basic Email Example (Gmail)
const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your_email@gmail.com', pass: 'your_app_password' // Use App Password if using Gmail with 2FA }});// Email optionsconst mailOptions = { from: 'your_email@gmail.com', to: 'recipient@example.com', subject: 'Hello from Node.js!', text: 'This is a plain text email.', html: '<h1>Hello 👋</h1><p>This is an HTML email.</p>'};// Send the emailtransporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log('Error:', error); } console.log('Email sent:', info.response);});
🔐 Gmail Security Note
If you're using Gmail, you need to:
Enable 2-Step Verification
Create an App Password in your Google account settings
📧 You Can Also:
Attach files with
attachments
Use templates (e.g., handlebars, pug, ejs)
Send to multiple recipients
📎 Send Email with Attachment Example
const mailOptions = { from: 'your_email@gmail.com', to: 'recipient@example.com', subject: 'With Attachment', text: 'Check the attached file.', attachments: [ { filename: 'file.txt', path: './file.txt' } ]};