What is nodemailer?
Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default.
Why nodemailer?
Nodemailer features
A single module with zero dependencies β code is easily auditable, as there are no dark corners
Heavy focus on security, no-one likes RCE vulnerabilities
Unicode support to use any characters, including emoji πͺ
Windows support β you can install it with npm on Windows just like any other module, there are no compiled dependencies. Use it hassle free from Azure or from your Windows box
Use HTML content, as well as plain text alternative
Add Attachments to messages
Embedded image attachments for HTML content β your design does not get blocked
Secure email delivery using TLS/STARTTLS
Different transport methods in addition to the built-in SMTP support
Sign messages with DKIM
Custom Plugin support for manipulating messages
Sane OAuth2 authentication
Proxies for SMTP connections
ES6 code β no more unintentional memory leaks, due to hoisted varβs
Autogenerated email test accounts from Ethereal.email`
Step by Step guide on how to send mail
- Open terminal.
mkdir node-mail cd node-mail
- Create server.js file.
touch server.js
- Create a node app.
npm init -y
- Install express and nodemailer.
npm install nodemailer express
- Create transportOptions.js and message.js.
touch message.js transportOptions.js
- Open message.js and export an object.
module.exports = (email)=>{ return { from: "test@mail.com", to: email, subject:"Sample mail ", text: "Hello", html: "<h1 style="color:#183b56;font-size: 28px;text-align: center;">Hello User</h1> <p style="font-size: 18px;color: #1f2933;text-align: center;">Hello this is a test mail</p>", } };
- Open transportOptions.js and export an object here also.
module.exports = transportOptions = { host: "smtp.office365.com", port: "587", auth: { user: "test@mail.com", pass: "PASSWORD" }, secureConnection: true, tls: { ciphers: "SSLv3" }, };
- Open server.js and create an express server.
const express = require('express'); const transportOptions = require('./transportOptions'); const message = require('./message'); const app = express(); app.get('/send-mail', (req, res) => { const {email} = req.body; (async () => { try { const mailTransport = nodemailer.createTransport(transportOptions); await mailTransport.sendMail(message(email)); return res.status(200).json({ message: "Successfully sent mail!", }); } catch (err) { return res.status(400).json({ message: "Sorry No such Email Exist", }); } })(); }); app.listen(3000, () => console.log('Example app is listening on port 3000.'));
- Save all files and test.
- Please comment for any suggestion or feedback.
- You can contact me on HimanshuMishra@duck.com
Top comments (0)