In Node.js, sending emails is simple and efficient with the help of the Nodemailer package.
Why Use Node.js for Sending Emails?
Node.js is a powerful backend framework that simplifies handling asynchronous tasks like sending emails. It ensures that the email-sending process doesn’t block other parts of your application, making it fast and efficient.
Tool for Sending Emails in Node.js: Nodemailer
Nodemailer is the most popular package for sending emails in Node.js. It supports:
- Sending plain text and HTML emails.
- Adding attachments to emails.
- Authentication with popular email services (e.g., Gmail, Outlook).
Setting Up the Project
Step 1: Create a New Node.js Project
Initialize a new project:
npm init -y
Install Nodemailer:
npm install nodemailer
Step 2: Import Nodemailer
Add the following line to your script:
const nodemailer = require('nodemailer');
Sending a Basic Email
Step 3: Configure the Email Transporter
The transporter is used to connect to your email service. You can use services like Gmail, Outlook, or a custom SMTP server.
const transporter = nodemailer.createTransport({
service: 'gmail', // Use Gmail
auth: {
user: 'your-email@gmail.com', // Your email
pass: 'your-email-password', // Your email password
},
});
Step 4: Define the Email Options
Email options include the recipient’s address, subject, and body of the email.
const mailOptions = {
from: 'your-email@gmail.com', // Sender's email
to: 'recipient-email@gmail.com', // Receiver's email
subject: 'Welcome to Node.js Email Tutorial!',
text: 'This is a simple text email sent from Node.js.', // Plain text body
};
Step 5: Send the Email
Use the sendMail() method to send the email:
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.error('Error sending email:', err);
} else {
console.log('Email sent successfully:', info.response);
}
});
Sending an HTML Email
You can send more visually appealing emails by using HTML content.
Example: Sending an HTML Email
const htmlMailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@gmail.com',
subject: 'HTML Email from Node.js',
html: `
<h1>Welcome to Node.js Email Tutorial!</h1>
<p>This is an email sent with HTML content.</p>
`,
};
transporter.sendMail(htmlMailOptions, (err, info) => {
if (err) {
console.error('Error sending email:', err);
} else {
console.log('HTML email sent successfully:', info.response);
}
});
Adding Attachments
You can attach files to your emails using the attachments property.
Example: Sending an Email with Attachments
const attachmentMailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@gmail.com',
subject: 'Email with Attachment',
text: 'Please find the attached file.',
attachments: [
{
filename: 'example.txt', // File name
path: './example.txt', // File path
},
],
};
transporter.sendMail(attachmentMailOptions, (err, info) => {
if (err) {
console.error('Error sending email:', err);
} else {
console.log('Email with attachment sent successfully:', info.response);
}
});
Using Environment Variables for Security
It’s not a good practice to hard-code your email credentials in the script. Instead, use environment variables.
Install the dotenv
package:
npm install dotenv
Create a .env file in your project directory and add your credentials:
EMAIL=your-email@gmail.com
PASSWORD=your-email-password
Load the environment variables in your script:
require('dotenv').config();
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
});
Real-World Use Case: Sending Verification Emails
When a user signs up for your application, you may need to send a verification email.
Example: Sending a Verification Email
const sendVerificationEmail = (email, verificationLink) => {
const mailOptions = {
from: 'your-email@gmail.com',
to: email,
subject: 'Verify Your Email',
html: `
<h2>Welcome!</h2>
<p>Please verify your email by clicking the link below:</p>
<a href="${verificationLink}">Verify Email</a>
`,
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.error('Error sending verification email:', err);
} else {
console.log('Verification email sent:', info.response);
}
});
};
// Example usage
sendVerificationEmail('user-email@gmail.com', 'https://example.com/verify?token=12345');
Troubleshooting Common Errors
- Authentication Error:
Ensure your email and password are correct. If using Gmail, enable “Less secure app access” or set up an app-specific password. - Connection Error:
Check if your SMTP server configuration is correct. - Blocked Email:
Some email providers may flag your email as spam. To avoid this, add SPF, DKIM, and DMARC records to your domain settings.
Common Nodemailer Methods
- createTransport(): Configures the email transporter.
- sendMail(): Sends an email with the specified options.
- verify(): Checks if the transporter is configured correctly.
Example: Verifying the Transporter
transporter.verify((err, success) => {
if (err) {
console.error('Transporter setup failed:', err);
} else {
console.log('Transporter is ready to send emails.');
}
});