🧰 Node.js File & Server Operations
Estimated reading: 4 minutes 22 views

✉️ Node.js – Sending Emails – Use Nodemailer to Send Emails from Your App


🧲 Introduction – Why Send Emails with Node.js?

Sending emails is a core feature in many backend applications—whether it’s for user registration, password reset, notifications, or alerts. Node.js doesn’t include built-in email functionality, but it integrates seamlessly with libraries like nodemailer, which enables you to send emails through SMTP servers like Gmail, Outlook, and custom domains.

🎯 In this guide, you’ll learn:

  • How to install and configure Nodemailer
  • Send emails with Gmail SMTP
  • Add attachments and HTML content
  • Common authentication errors and best practices

📦 Step 1 – Install Nodemailer

npm install nodemailer

📧 Step 2 – Basic Example to Send an Email

const nodemailer = require('nodemailer');

// Create transporter using Gmail SMTP
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your_email@gmail.com',
    pass: 'your_gmail_app_password' // Use app password, not regular one
  }
});

// Define email options
let mailOptions = {
  from: 'your_email@gmail.com',
  to: 'recipient@example.com',
  subject: 'Test Email from Node.js',
  text: 'Hello! This is a plain text email sent using Node.js.'
};

// Send email
transporter.sendMail(mailOptions, (error, info) => {
  if (error) return console.error(error);
  console.log('Email sent:', info.response);
});

🧪 Output in Terminal:

Email sent: 250 2.0.0 OK 1234567890abcdef

📬 Recipient gets a plain text email in their inbox.


💡 Gmail App Password Note

Google no longer allows less-secure apps to access Gmail. You must enable 2FA and use an App Password from your Google Account to send emails.


🎨 Step 3 – Send HTML Emails with Attachments

let mailOptions = {
  from: 'your_email@gmail.com',
  to: 'recipient@example.com',
  subject: 'Styled Email with Attachment',
  html: '<h1>Hello User</h1><p>This is an HTML message.</p>',
  attachments: [
    {
      filename: 'file.txt',
      path: './file.txt'
    }
  ]
};

📎 This will send an email with rich HTML content and file.txt attached.


🧪 Example – Sending to Multiple Recipients

let mailOptions = {
  from: 'your_email@gmail.com',
  to: 'first@example.com, second@example.com',
  subject: 'Group Email',
  text: 'Sent to multiple users!'
};

📊 Nodemailer Configuration Options

OptionDescription
serviceEmail provider (e.g., Gmail, Outlook, Yahoo)
hostSMTP host (used for custom email servers)
portSMTP port (465 for SSL, 587 for TLS)
securetrue for SSL, false for TLS
auth.userSender’s email address
auth.passApp password or actual password (use env variables)

🧱 Best Practices for Sending Emails

✅ Tip💡 Why It Matters
Use environment variablesAvoid hardcoding credentials
Use HTML templates for formattingBetter UX for marketing or transactional emails
Add error handling on sendMail()Handle failures gracefully
Avoid sending emails in loopsBatch emails or use queue systems
Use verified SMTP servicesPrevent spam filtering and rejection

📌 Summary – Recap & Next Steps

Node.js lets you send rich, formatted, and attachment-enabled emails using nodemailer. It supports plain SMTP, OAuth, HTML templates, and file attachments—making it a great choice for production-ready mail features.

🔍 Key Takeaways:

  • Use nodemailer for sending emails with Node.js
  • Always use Gmail app passwords (or SMTP services) for auth
  • Include HTML and attachments using options
  • Never expose email credentials in source code

⚙️ Real-world relevance:
Used in signup forms, password resets, alert systems, eCommerce receipts, contact forms, and CRM systems.


❓FAQs – Sending Emails in Node.js


Why is Gmail rejecting my login in nodemailer?
✅ Google blocks less-secure apps. You must enable 2-step verification and generate an App Password from your Google account.


Can I send HTML emails with nodemailer?
✅ Yes. Use the html field in your mail options:

html: "<h1>Hello!</h1><p>This is HTML</p>"

How do I send emails from a custom domain?
✅ Use SMTP configuration:

host: 'smtp.yourdomain.com',
port: 587,
secure: false,
auth: { user: 'you@yourdomain.com', pass: 'yourpass' }

Can I use nodemailer with Outlook or Yahoo?
✅ Yes. Set service: 'outlook' or use host config like:

host: 'smtp-mail.outlook.com', port: 587

Is nodemailer production-ready?
✅ Yes. It’s stable and used in thousands of production Node.js apps.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

✉️ Node.js – Sending Emails

Or Copy Link

CONTENTS
Scroll to Top