How to Send Email Programmatically (with Node.js)
Sometimes you want to send emails at scale: cold leads, hiring managers, transactions. Instead of handwriting each email in Gmail (or any other email client) you can programmatically send emails using Node.js. There are many ways to send emails, but in this tutorial we will use nodemailer
. It is suggested to have a Gmail account and send via app password, but it is not required. It is super simple.
Install Nodemailer
First, create a folder/repository on a computer and install nodemailer
. Nodemailer is a popular Node.js module that greatly simplifies the process of sending emails from your Node.js applications.
npm install nodemailer
Set Up Your Email Configuration
Create a file, say email.js
, and configure the SMTP settings for your email service provider (like Gmail, Outlook, etc.). When using Gmail, you'll need to create an app password.
const nodemailer = require('nodemailer');
// Create a transporter
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-email-password'
}
});
// Define the email options
let mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@example.com',
subject: 'Hello from Node.js',
text: 'This is a test email sent from Node.js!',
html: '<b>This is a test email sent from Node.js!</b>' // Optional: to send HTML content
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Email sent: ' + info.response);
});
and run the script with:
node ./email.js
Sending emails with code is made simple with packages like nodemailer
and can an easy way to scale sending email.