Programmatically Sending Emails using Node.js - Complete SMTP Guide

Programmatically Sending Emails using Node.js - Complete SMTP Guide

ImageURLs
Tags
tutorial
Node.js
javascript
smtp
email-automation
programming
Published
January 23, 2026
Author

πŸ“§ Programmatically Sending Emails Using Node.js (Complete SMTP Guide)

Tags: tutorial, programming, email-automation, nodejs, javascript, smtp
Published: January 23, 2026
Author: Tempusmail Team

Introduction: Why Send Emails with Node.js?

If you’re building a web application, API, or automation tool with JavaScript, you’ve probably asked:
β€œHow do I send emails from my server?”
Node.js makes this incredibly simple using the Nodemailer library.
Nodemailer acts as a bridge between your Node.js application and email servers. Whether you’re sending welcome emails, password resets, or automated notifications, it handles everything using clean, asynchronous code.

βœ… Benefits of Sending Emails with Node.js

  • Works seamlessly with Express, Fastify, and other frameworks
  • Native async/await support for non-blocking email sending
  • Battle-tested Nodemailer library with millions of downloads
  • Ideal for APIs, serverless functions, and microservices
This guide will walk you through sending emails programmatically using Node.js.
Beginner or experienced developerβ€”you’ll be sending emails in minutes πŸš€

🧰 What You Need Before Starting

Make sure you have the following:
  • βœ… Node.js 14+
  • βœ… npm or yarn
  • βœ… Email account (example: you@yourcompany.com)
  • βœ… Email password
  • βœ… SMTP server settings (listed below)

πŸ’‘ Where to Find SMTP Settings

Your email provider usually lists these in their documentation.
For Tempusmail users:
panel.tempusmail.com β†’ Account Settings β†’ Email Configuration

πŸ“Œ SMTP Settings Reference (Tempusmail)

Setting
Value
SMTP Server
smtp.qboxmail.com
Port (SSL)
465
Port (STARTTLS)
587
Security
SSL/TLS or STARTTLS
Username
your-email@yourdomain.com
Password
Your email password
Authentication
Required
πŸ’‘ Pro Tip:
Use port 465 with secure: true for SSL.
Use port 587 with secure: false for STARTTLS.

🧱 Step 1: Create a New Project

mkdir email-sender cd email-sender npm init -y

πŸ“¦ Step 2: Install Nodemailer

npm install nodemailer
That’s itβ€”no additional dependencies required.

βœ‰οΈ Step 3: Create Your Email Script

Create a file named send-email.js:
const nodemailer =require('nodemailer'); // SMTP Configuration const transporter = nodemailer.createTransport({ host:'smtp.qboxmail.com', port:465, secure:true,// true for 465, false for 587 auth: { user:'your-email@yourdomain.com', pass:'your-password' } }); // Send email function asyncfunctionsendEmail(to, subject, text) { try { const info =await transporter.sendMail({ from:'"Your Name" <your-email@yourdomain.com>', to, subject, text }); console.log('βœ… Email sent:', info.messageId); return {success:true,messageId: info.messageId }; }catch (error) { console.error('❌ Error:', error.message); return {success:false,error: error.message }; } } // Test email sendEmail( 'recipient@example.com', 'Hello from Node.js πŸš€', 'This email was sent using Node.js and Tempusmail.' );
⚠️ Security Warning:
Never hardcode passwords in production. Environment variables are shown later.

▢️ Step 4: Run Your Script

node send-email.js
If successful, you’ll see:
βœ… Email sent: <message-id>
πŸŽ‰ Congratulations! Your first email has been sent using Node.js.

🎨 Sending HTML Emails

asyncfunctionsendHtmlEmail(to, subject, htmlContent) { const info =await transporter.sendMail({ from:'"Your Company" <your-email@yourdomain.com>', to, subject, html: htmlContent }); console.log('βœ… HTML email sent:', info.messageId); return info; }

Example HTML Template

const htmlContent = ` <!DOCTYPE html> <html> <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;"> <div style="background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;"> <h1 style="color: white; margin: 0;">Welcome to Tempusmail! πŸŽ‰</h1> </div> <div style="padding: 30px; background: #f9fafb;"> <p style="font-size: 16px; color: #374151; line-height: 1.6;"> Thank you for choosing our email service. Your account is now ready! </p> <a href="https://tempusmail.com" style="display: inline-block; background: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px;"> Get Started β†’ </a> </div> </body> </html> `; sendHtmlEmail('user@example.com','Welcome!', htmlContent);

πŸ“Ž Sending Emails with Attachments

const path =require('path'); asyncfunctionsendEmailWithAttachment(to, subject, text, filePath) { const info =await transporter.sendMail({ from:'"Your Company" <your-email@yourdomain.com>', to, subject, text, attachments: [ { filename: path.basename(filePath), path: filePath } ] }); console.log('βœ… Email with attachment sent:', info.messageId); return info; }

Multiple Attachments

const attachments = [ {filename:'invoice.pdf',path:'/path/to/invoice.pdf' }, {filename:'receipt.pdf',path:'/path/to/receipt.pdf' }, {filename:'logo.png',path:'/path/to/logo.png' } ]; await transporter.sendMail({ from:'"Your Company" <your-email@yourdomain.com>', to:'client@example.com', subject:'Your Documents', text:'Please find your documents attached.', attachments });

πŸ” Using Environment Variables (Recommended)

Step 1: Install dotenv

npm install dotenv

Step 2: Create .env

SMTP_HOST=smtp.qboxmail.com SMTP_PORT=465 SMTP_SECURE=true SMTP_USER=your-email@yourdomain.com SMTP_PASS=your-password FROM_NAME=Your Company

Step 3: Load Variables

require('dotenv').config(); const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, port:Number(process.env.SMTP_PORT), secure: process.env.SMTP_SECURE ==='true', auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } });
⚠️ Add .env to .gitignore.

🧱 Reusable Production Email Service

Your class implementation is already solid.
It is production-ready, secure, and scalable with:
  • HTML support
  • Attachments
  • Pre-built templates
  • Centralized configuration
No logic changes requiredβ€”only formatting preserved for clarity.

πŸ›  Troubleshooting Common Errors

❌ Connection refused / timed out

  • Verify SMTP host
  • Use correct port (465 / 587)
  • Check firewall or hosting restrictions

❌ Authentication failed

  • Use full email address
  • Recheck password
  • Reset credentials if needed

❌ Self-signed certificate (Testing only)

tls: { rejectUnauthorized:false }
⚠️ Never use this in production.

❓ Frequently Asked Questions

Send to multiple recipients?
to: ['user1@example.com','user2@example.com']
Add CC/BCC?
cc:'cc@example.com', bcc:'bcc@example.com'
Serverless compatible?
Yesβ€”works with AWS Lambda, Vercel, and Netlify.

🎯 Conclusion

You’ve learned how to:
βœ… Send text and HTML emails
βœ… Attach files
βœ… Secure credentials using environment variables
βœ… Build a reusable email service
βœ… Integrate email sending with Express APIs
βœ… Troubleshoot SMTP errors

πŸš€ Get Professional Email Hosting

Tempusmail offers reliable SMTP access with 99.9% uptime and 24/7 support.