Utilize Nodemailer SMTP for Sending Emails in Express.js

Posted by

How to Send Emails in Express.js with Nodemailer SMTP

Sending Emails in Express.js with Nodemailer SMTP

Express.js is a popular web application framework for Node.js, and Nodemailer is a module for Node.js that allows you to send emails easily. In this tutorial, we will show you how to send emails using Nodemailer SMTP in an Express.js application.

First, you will need to install Nodemailer in your Express.js project. You can do this by running the following command in your terminal:

npm install nodemailer

Next, you will need to require Nodemailer in your Express.js application. Add the following line of code at the top of your app.js file:

const nodemailer = require('nodemailer');

Now, you can create a Nodemailer transport object with your SMTP server settings. Here is an example of how you can do this:

const transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'your-email@example.com',
pass: 'your-password'
}
});

Once you have created the transporter object, you can use it to send emails. Here is an example of how you can send an email using Nodemailer in Express.js:

app.post('/send-email', (req, res) => {
const { to, subject, text } = req.body;

const mailOptions = {
from: 'your-email@example.com',
to: to,
subject: subject,
text: text,
};

transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.status(500).send('Error sending email');
} else {
res.send('Email sent successfully');
}
});
});

Don’t forget to add the necessary form fields in your HTML file to send the email data to the server. You can use a simple form with input fields for the recipient’s email address, subject, and message.

With these steps, you can easily send emails in an Express.js application using Nodemailer SMTP. Happy coding!

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@JagadishL-wj6sn
6 months ago

Do have any idea about fixing the delivery issue.

@BoyGirl-ds5cv
6 months ago

Bro can we communicate online

@arupde6320
6 months ago

be regular