Skip to content

Instantly share code, notes, and snippets.

@nanusdad
Last active March 25, 2024 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanusdad/2c67c536487ed3b791e5a60c73ab2134 to your computer and use it in GitHub Desktop.
Save nanusdad/2c67c536487ed3b791e5a60c73ab2134 to your computer and use it in GitHub Desktop.
Simple ExpressJS API to use local sendmail

Simple ExpressJS API to use local sendmail

API code

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

app.use(express.json());

// Configure Nodemailer to use the local sendmail service
const transporter = nodemailer.createTransport({
  sendmail: true,
  newline: 'unix',
  path: '/usr/sbin/sendmail'
});

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

  // Set up email data
  const mailOptions = {
    from: '"No Name" <noreply@somewhere.com>', // sender address
    to, // list of receivers
    subject, // Subject line
    text, // plain text body
  };

  // Send email with the defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.status(200).json({ message: 'Email sent successfully', info });
  });
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Testing with cURL

 curl -X POST http://localhost:3000/send-email -H "Content-Type: application/json" -d '{"to": "test@example.com", "subject": "Hello from Express", "text": "This is a test email sent from the Express.js API using sendmail."}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment