0
0
ExpressHow-ToBeginner · 4 min read

How to Create Email Service in Express: Simple Guide

To create an email service in Express, use the Nodemailer package to send emails. Set up a transporter with your email provider's SMTP settings, then create routes in Express to handle email sending requests.
📐

Syntax

Here is the basic syntax to set up an email service in Express using Nodemailer:

  • nodemailer.createTransport(): Configures the email server details.
  • transporter.sendMail(): Sends the email with specified options.
  • Express route: Handles HTTP requests to trigger email sending.
javascript
import express from 'express';
import nodemailer from 'nodemailer';

const app = express();
app.use(express.json());

const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: 'your-email@example.com',
    pass: 'your-email-password'
  }
});

app.post('/send-email', async (req, res) => {
  const { to, subject, text } = req.body;
  try {
    await transporter.sendMail({
      from: 'your-email@example.com',
      to,
      subject,
      text
    });
    res.send('Email sent successfully');
  } catch (error) {
    res.status(500).send('Error sending email');
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));
💻

Example

This example shows a complete Express app that sends an email when you POST to /send-email with JSON containing to, subject, and text. It uses Nodemailer with Gmail SMTP.

javascript
import express from 'express';
import nodemailer from 'nodemailer';

const app = express();
app.use(express.json());

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'yourgmail@gmail.com',
    pass: 'your-app-password'
  }
});

app.post('/send-email', async (req, res) => {
  const { to, subject, text } = req.body;
  try {
    await transporter.sendMail({
      from: 'yourgmail@gmail.com',
      to,
      subject,
      text
    });
    res.send('Email sent successfully');
  } catch (error) {
    res.status(500).send('Failed to send email');
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
Server running on port 3000 // When POST /send-email with JSON {"to":"friend@example.com","subject":"Hello","text":"Hi there!"} // Response: Email sent successfully
⚠️

Common Pitfalls

Common mistakes when creating an email service in Express include:

  • Not enabling express.json() middleware to parse JSON body.
  • Using incorrect SMTP settings or forgetting to allow less secure apps in email provider settings.
  • Not handling errors from sendMail, causing the server to crash.
  • Hardcoding sensitive credentials instead of using environment variables.
javascript
/* Wrong: Missing JSON parser middleware */
app.post('/send-email', (req, res) => {
  // req.body will be undefined
  const { to, subject, text } = req.body;
  // This will cause an error
});

/* Right: Add JSON parser middleware */
app.use(express.json());

app.post('/send-email', (req, res) => {
  const { to, subject, text } = req.body;
  // Now req.body is parsed correctly
});
📊

Quick Reference

Tips for creating email service in Express:

  • Use nodemailer.createTransport() with correct SMTP or service settings.
  • Always parse JSON body with express.json().
  • Use environment variables for email credentials.
  • Handle errors in sendMail to avoid crashes.
  • Test sending emails with simple text before adding HTML or attachments.

Key Takeaways

Use Nodemailer with Express to send emails via SMTP or email services.
Always include express.json() middleware to parse incoming JSON requests.
Store email credentials securely using environment variables, not hardcoded values.
Handle errors from the email sending function to keep your server stable.
Test your email service with simple requests before adding complexity.