Express.js Email Integration Guide

Integrate MailPort cleanly into Express.js route handlers with environment variables and error handling:

import express from 'express';
import { createMailer, smtp, MailError } from 'mailport';

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

const mailer = createMailer({
  transport: smtp({
    host: process.env.SMTP_HOST!,
    port: Number(process.env.SMTP_PORT) || 587,
    auth: {
      user: process.env.SMTP_USER!,
      pass: process.env.SMTP_PASSWORD!,
    },
  }),
});

app.post('/api/send-welcome', async (req, res) => {
  try {
    const result = await mailer.send({
      from: 'app@example.com',
      to: req.body.email,
      subject: 'Welcome to our platform',
      text: 'Thanks for signing up.',
    });

    res.json({ success: true, messageId: result.id });
  } catch (err) {
    if (err instanceof MailError) {
      res.status(400).json({ error: err.message, code: err.code, retryable: err.retryable });
    } else {
      res.status(500).json({ error: 'Internal server error' });
    }
  }
});

app.listen(3000);