How to Send Emails with Express.js?

How to Send Emails with Express.js?


In today's digital world, communicating via email has become more important than ever. In web applications, it is used to communicate with users as well as to send notifications, user verifications, or marketing emails. In this article, you will learn the basic ways to send emails in a Node.js application using Express.js.

Introduction to Sending Emails with Node.js and Express.js

Node.js is a popular platform used to run JavaScript code on the server side. Express.js, on the other hand, is a framework that runs on Node.js and makes it easier to develop web applications. For email sending, the nodemailer library is generally used. This library allows you to easily send emails using the SMTP (Simple Mail Transfer Protocol) protocol.

Installing the Nodemailer Library

First, you need to install the nodemailer library in your project. You can do this by running the following command in the terminal:

npm install nodemailer

Creating an Application that Sends Email

Below is an example application that simply sends an email using Express.js:

const express = require('express');
const nodemailer = require('nodemailer');

const app = express();
const PORT = process.env.PORT || 3000;

// Email sending settings
let transporter = nodemailer.createTransport({
    host: 'smtp.example.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
        user: 'your-email@example.com', // Your email address if not using OAUTH2 in Gmail
        pass: 'your-password', // Your email password
    },
});

app.get('/send-email', (req, res) => {
    let mailOptions = {
        from: 'sender@example.com', // Sender email address
        to: 'recipient@example.com', // Recipient email address
        subject: 'Test Email', // Email subject
        text: 'Hello, this is a test email!', // Email content
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.status(500).send(error.toString());
        }
        res.status(200).send('Email sent: ' + info.response);
    });
});

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}.`);
});

The above code sets up an Express.js server and sends an email when a GET request is made to a specific URL path /send-email. With the createTransport function, the email server configuration is done. When you run the application and send a GET request to the specified URL, you will see that the email is sent.

Conclusion

Sending emails with Express.js is an effective way to interact with your users. By using the nodemailer library, you can implement a wide variety of email scenarios and make your application more interactive. Be sure to properly configure all email-related settings in your application and check the usage limitations. For more information about sending emails, you can refer to the official Nodemailer documentation.