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.
First, you'll need to set up a new Node.js project for sending emails.
mkdir emailtest cd emailtest
{ "name": "emailtest", "version": "1.0.0", "main": "index.js", "dependencies": { "nodemailer": "^6.0.0" } }
npm install
Now that your project is set up, let's send a simple 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); } });
node index.js
You should see a confirmation that the email was sent.
If you need to send files with your email, NodeMailer makes it easy.
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 } ] };
HTML emails can make your messages more engaging with formatting, images, and links.
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>' };
It's important to handle errors to ensure your application works smoothly.
transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log('Error:', error.message); } else { console.log('Email sent:', info.response); } });
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.
The above is the detailed content of Mastering Email Sending in Node.js: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!