DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

Building a Simple Email Sending API with Express and Node.js

In this blog post, we'll walk through creating a simple email sending API using Express and Node.js.

Setting Up the Environment

To get started, let's set up a basic Express server that will handle API requests for sending emails. Here's an overview of the project structure:

Project Structure

project-root
│   index.js
│
├── routes
│   └── email.js
│
├── controllers
│   └── email.js
│
└── utils
    └── sendEmails.js
Enter fullscreen mode Exit fullscreen mode

Getting Started with Code

1. Setting Up the Server (index.js)

Our index.js file initializes the Express server, sets up middleware, and defines routes for handling email-related requests.

const express = require("express");
const cors = require("cors");
const PORT = process.env.PORT || 3000;

require("dotenv").config();

const app = express();

app.use(express.json());

app.use(cors({
    origin: ['http://localhost:3000'],
    credentials: true,
}));

app.use("/api", require("./routes/email"));

app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

2. Creating the Email Route (email.js)

We define an email route in routes/email.js to handle POST requests for sending emails.

const express = require('express');
const router = express.Router();
const { sendEmail } = require('../controllers/email.js');

router.post('/data', sendEmail);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

3. Handling Email Sending Logic (controllers/email.js)

The controllers/email.js file contains the logic to handle email sending based on the received request.

const sendEmail = require("../utils/sendEmails");

require("dotenv").config();

exports.sendEmail = async (req, res) => {
    try {
        const { email, message } = req.body;

        if (!email) {
            return res.status(400).json({ message: "Email is required." });
        }

        const options = {
            to: email,
            subject: "Test",
            message: message,
        };

        await sendEmail(options);

        res.status(200).json({
            message: "Check your mail!",
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: "Internal server error" });
    }
};
Enter fullscreen mode Exit fullscreen mode

4. Email Sending Utility (utils/sendEmails.js)

The utils/sendEmails.js file contains the function responsible for sending emails using Nodemailer.

const nodeMailer = require("nodemailer");

const sendEmail = async (options) => {
    const transporter = nodeMailer.createTransport({
        host: process.env.SMPT_HOST,
        port: process.env.SMPT_PORT,
        service: process.env.SMPT_SERVICE,
        auth: {
            user: process.env.SMPT_MAIL,
            pass: process.env.SMPT_APP_PASS,
        },
    });

    const mailOptions = {
        from: process.env.SMPT_MAIL,
        to: options.to,
        subject: options.subject,
        html: options.message,
    };

    await transporter.sendMail(mailOptions);
};

module.exports = sendEmail;
Enter fullscreen mode Exit fullscreen mode

Configuration and Testing

Before running this application, ensure you have the necessary environment variables set in a .env file containing your SMTP configuration.

SMPT_HOST=your_smtp_host
SMPT_PORT=your_smtp_port
SMPT_SERVICE=your_smtp_service
SMPT_MAIL=your_email_address
SMPT_APP_PASS=your_email_app_password
Enter fullscreen mode Exit fullscreen mode

Once configured, start your server using node index.js and test the API using tools like Postman or by sending requests from your frontend application.

Conclusion

Congratulations! You've now created a basic API using Express and Node.js to facilitate email sending. This simple setup can be expanded and enhanced to suit more complex requirements by adding features like email templates, attachments, or error handling for various scenarios.

Reference

For detailed implementation, you can refer to the following GitHub repository:

Node.js Nodemailer Example Repository

Top comments (4)

Collapse
 
victor_gadelha profile image
João Victor Gadelha

Great article. I'm currently learning about making API and this was useful. When I make a Fullstack project, I'm certainly gonna try it.

I'm also thinking about write some articles for beginners like me and your text gave some ideas how I could do it.

Collapse
 
manthanank profile image
Manthan Ankolekar

Thanks!😁

Collapse
 
soydiego profile image
Diego Franchina

Great only you should modify the typo in the variables. The correct name is SMTP instead of SMPT 😊

Collapse
 
manthanank profile image
Manthan Ankolekar

Yes😁