NodeMailer: Send Email from Nodejs Application
Send Emails are becoming important in every application. So, In this article, we will see how we can send Emails in the nodejs applications. I will be using a package called “Nodemailer” to send emails. To test the application we will be using “mailtrap” which is a free service to test.
Note:
You cant add a nodemailer package to the frontend. It is a node package.
Prerequisites:
- Nodejs installed
- local running server.
You can check out the articles here for the above prerequisites:
https://mdpuneethreddy.com/expressjs-how-to-start-with-nodejs-and-express
Objectives:
- Install Nodemailer
- Add Post request in backend
- mailtrap.io to test the endpoint
- Send Email
Install Nodemailer:
You can add the Nodemailer package using yarn or npm. I will be using yarn
yarn add nodemailer
Add Post request in the backend :
We will create an endpoint to send the email. Here I will be creating a post request to send the email.
app.post("/api/sendMail",(req,res)=>{
})
Send Email:
- Import nodemailer into the file
import * as nodemailer from "nodemailer"
2. Further we can use Gmail to capture the traffic or we can use a testing site to capture the traffic. I would personally recommend having a testing site than your Gmail.
In this article, I will be using “mailtrap” to capture the traffic.
3. Below are the steps to create an account in mailtrap.
- visit link https://mailtrap.io/
- Next signup and login
- Select nodemailer in integartions, you can see something like below. In integrations, choose Nodemailer.
import * as nodemailer from "nodemailer"
------
var transport = nodemailer.createTransport({
host: "smtp.mailtrap.io",
port: 2525,
auth: {
user: "username"
pass: "password"
}
});
------
app.post("/api/sendMail",(req,res)=>{
})
Final Code
import * as nodemailer from "nodemailer"
const transport = nodemailer.createTransport({
host: "smtp.mailtrap.io",
port: 2525,
auth: {
user: "username"
pass: "password"
}
});
app.post("/api/sendMail",(req,res)=>{
const mailOptions = {
from: you@gmail.com// host address
to: client@gamil.com,
subject: "test Email",
html: "Testing Mail"
};
transporter.sendMail(mailOptions, (err, info)=> {
if(err)
res.status(400).send({error:"failed to send"})
else
res.send({message:"Successfully sent"})
});
})