Skip to content

Instantly share code, notes, and snippets.

@nanusdad
Last active March 25, 2024 07:34
Show Gist options
  • 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" <[email protected]>', // 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": "[email protected]", "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