DEV Community

Cover image for NODEMAILER USING NODE
Vishwanath
Vishwanath

Posted on

NODEMAILER USING NODE

This article discusses how to configure nodemailer in your code. Quickly understand the code and implement your code. Let's start

Setup folder structure like this

folder structure

Packages

  • express

  • nodemailer

  • dotenv

  • colors

npm i express nodemailer dotenv colors

Create backend folder and inside folder create file is server.js,
Like this backend/server.js

backend/server.js

In this section, we create the express app server, and listen port is 5000.

import express from 'express';
import dotenv from 'dotenv';
import colors from 'colors';
import Router from './router.js';


dotenv.config();

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }))

app.use('/api/contact', Router);


const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
    console.log(`server running ${process.env.NODE_ENV} mode on port ${process.env.PORT}`.yellow.underline);
})
Enter fullscreen mode Exit fullscreen mode

backend/router.js

In this section configure the nodemailer and post your email, to email, subject, and message in the route http://localhost:5000/api/contact. Using the Postman really helps test your API. Easily find errors and nodemailer working or not

import express from 'express';
const router  = express.Router();
import nodemailer from 'nodemailer';


router.post('/', (req, res) => {

    const { fromEmail, toEmail, subject, message } = req.body;

    const output = `
        <div style="font-family:'Sen',sans-serif;">
            <h3>Subject</h3>
            <p style="margin-left: 1rem;">${subject}</p>
            <h3>Message</h3>
            <p style="margin-left: 1rem;">${message}</p>
        </div>
    `;

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        service: 'gmail',
        port: 465,
        secure: true, // use SSL // true for 465, false for other ports
        auth: {
            user: `${fromEmail}`, // generated ethereal user
            pass: '---------'  // generated ethereal password
        },
        tls:{
            rejectUnAuthorized:true
        }

    });

    // setup email data with unicode symbols
    let mailOptions = {
        from: `"Contact" <${fromEmail}>`, // sender address
        to: `${toEmail}`, // list of receivers
        subject: `${subject}`, // Subject line
        text: `${message}`, // plain text body
        html: output // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.status(401).json({
                msg: error
            });
        }
        // console.log('Message sent: %s', info.messageId);   
        // console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

        if (info) {
            return res.status(200).json({
                msg:`Message has been sent ${toEmail}`
            });
        }
    });

})



export default router;
Enter fullscreen mode Exit fullscreen mode

I trust this article helps your code and understand the configure the nodemailer.

Thanks for reading this article ❤

Github | Twitter

Top comments (0)