Sending emails is a common feature in many web applications, whether it's for user registration, password resets, or marketing campaigns. In this guide, we'll show you how to send emails using Node.js with the help of the NodeMailer module. We'll cover everything from setting up your project to sending HTML emails and handling attachments.
1. Getting Started with Your Node.js Email Project
First, you'll need to set up a new Node.js project for sending emails.
- Create a Project Folder
mkdir emailtest
cd emailtest
-
Initialize Your Project
Create a
package.json
file with the following content:
{
"name": "emailtest",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"nodemailer": "^6.0.0"
}
}
- Install NodeMailer Install the required NodeMailer module by running:
npm install
2. Sending Your First Email
Now that your project is set up, let's send a simple email.
-
Create an
index.js
File Add the following code to send an email:
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: 'smtp.freesmtpservers.com',
port: 25
});
const mailOptions = {
from: '"Test Email" <test@email.com>',
to: 'someone@example.com',
subject: 'Hello!',
text: 'Hello world!',
html: '<p>Hello world!</p>'
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log('Error:', error);
} else {
console.log('Email sent:', info.response);
}
});
- Run Your Code Run the code using Node.js:
node index.js
You should see a confirmation that the email was sent.
3. Adding Attachments to Your Email
If you need to send files with your email, NodeMailer makes it easy.
- Example with Attachments
const mailOptions = {
from: '"Test Email" <test@email.com>',
to: 'someone@example.com',
subject: 'Hello with Attachments!',
text: 'Please find the attached files.',
attachments: [
{
filename: 'test.txt',
path: './test.txt' // Local file
},
{
filename: 'example.txt',
content: 'This is a text file content.' // Content as string
}
]
};
4. Sending HTML Emails
HTML emails can make your messages more engaging with formatting, images, and links.
- HTML Email Example
const mailOptions = {
from: '"Test Email" <test@email.com>',
to: 'someone@example.com',
subject: 'Hello, HTML!',
html: '<h1>Hello world!</h1><p>This is an HTML email.</p>'
};
5. Handling Errors
It's important to handle errors to ensure your application works smoothly.
- Error Handling Example
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log('Error:', error.message);
} else {
console.log('Email sent:', info.response);
}
});
Conclusion
Sending emails using Node.js and NodeMailer is straightforward. With just a few lines of code, you can send plain text or HTML emails, attach files, and handle errors efficiently. As your needs grow, you can explore more advanced features like integrating with dedicated email services and managing asynchronous email queues.
Top comments (0)