Are you looking to add email functionality to your Node.js application? Whether you're building a contact form, sending notifications, or automating email workflows, this tutorial is your ultimate guide to getting started. Using Nodemailer, a powerful and easy-to-use Node.js library, we'll walk you through every step of sending emails programmatically. From setting up your project to sending emails with attachments, this tutorial is designed to be beginner-friendly while covering advanced features for seasoned developers.
By the end of this tutorial, you'll have a fully functional email-sending system integrated into your Node.js application. You'll also learn best practices like securing your credentials with environment variables and testing your setup with a fake SMTP server. Ready to take your Node.js skills to the next level? Dive into the tutorial and start sending emails like a pro today!
Before starting, ensure you have the following:
1. Create a new directory for your project:
mkdir nodemailer-tutorial
cd nodemailer-tutorial
2. Initialize a new Node.js project:
npm init -y
3. Install the Nodemailer library:
npm install nodemailer --save
Nodemailer requires a transport object to send emails. For this tutorial, we'll use Gmail as the email service provider.
1. Create a new file called index.js
:
touch index.js
2. Open the file and add the following code to set up Nodemailer:
1// Step 1: Import Nodemailer
2const nodemailer = require('nodemailer');
3
4// Step 2: Create a transporter object
5const transporter = nodemailer.createTransport({
6 service: 'gmail', // Use Gmail as the service
7 auth: {
8 user: '[email protected]', // Your Gmail address
9 pass: 'your-app-password', // Your Gmail app password (not your regular password)
10 },
11});
12
13// Step 3: Define email options
14const mailOptions = {
15 from: '[email protected]', // Sender address
16 to: '[email protected]', // Recipient address
17 subject: 'Hello from Nodemailer!', // Email subject
18 text: 'This is a test email sent using Nodemailer.', // Plain text body
19 html: '<h1>Hello!</h1><p>This is a test email sent using <b>Nodemailer</b>.</p>', // HTML body
20};
21
22// Step 4: Send the email
23transporter.sendMail(mailOptions, (error, info) => {
24 if (error) {
25 console.error('Error sending email:', error);
26 } else {
27 console.log('Email sent:', info.response);
28 }
29});
Since Gmail requires additional security for third-party apps, you'll need to generate an app password:
auth.pass
field in the code above.node index.js
Email sent: 250 2.0.0 OK 1234567890abcdef-1234567890abcdef
You can also send emails with attachments using Nodemailer. Update the mailOptions
object as follows:
1const mailOptions = {
2 from: '[email protected]',
3 to: '[email protected]',
4 subject: 'Email with Attachment',
5 text: 'This email contains an attachment.',
6 html: '<h1>Check this out!</h1><p>This email contains an attachment.</p>',
7 attachments: [
8 {
9 filename: 'example.txt', // Name of the attachment
10 content: 'This is a text file attachment.', // Content of the attachment
11 },
12 {
13 filename: 'image.png', // Name of the image attachment
14 path: __dirname + '/image.png', // Path to the image file
15 },
16 ],
17};
For security reasons, avoid hardcoding sensitive information like email credentials. Use environment variables instead:
dotenv
package:npm install dotenv
.env
file:touch .env
.env
file:EMAIL_USER=[email protected]
EMAIL_PASS=your-app-password
index.js
to use environment variables:1require('dotenv').config();
2
3const transporter = nodemailer.createTransport({
4 service: 'gmail',
5 auth: {
6 user: process.env.EMAIL_USER,
7 pass: process.env.EMAIL_PASS,
8 },
9});
If you don't want to use a real email account, you can test your code using a fake SMTP server like Mailtrap:
transporter
configuration:1const transporter = nodemailer.createTransport({
2 host: 'sandbox.smtp.mailtrap.io',
3 port: 2525,
4 auth: {
5 user: 'your-mailtrap-username',
6 pass: 'your-mailtrap-password',
7 },
8});
You've successfully learned how to send emails using Node.js and Nodemailer! You can now:
Feel free to explore Nodemailer's official documentation for more advanced features like templates, custom SMTP servers, and more.