Prompt
How to send email from Express
Latest observation
You can send email from an Express.js app using libraries like Nodemailer (SMTP-based) or modern email APIs (SendLayer, Resend, Postmark). The simplest approach is to set up a route in Express that calls Nodemailer with your credentials, or use an API provider for better deliverability and security.
🔧 Using Nodemailer (SMTP)
Install dependencies
bash
npm install express nodemailer body-parser dotenv
Configure transporter
js
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
- service: "gmail", // or outlook, yahoo, etc.
- auth: {
- user: process.env.EMAIL_USER,
- pass: process.env.EMAIL_PASS
}
});
Create route in Express
js
app.post("/send-email", async (req, res) => {
const { to, subject, text } = req.body;
try {
- await transporter.sendMail({ from: process.env.EMAIL_USER, to, subject, text });
res.send("Email sent successfully!");
} catch (err) {
res.status(500).send("Error sending email");
}
});
🌐 Using Email APIs (No SMTP)
If you don’t want to deal with SMTP, use an API provider:
SendLayer / Resend / Postmark / SendGrid
Sign up and get an API key.
Verify your domain (SPF/DKIM setup).
Use fetch or axios in your Express route to call their HTTPS endpoint.
js
const axios = require("axios");
app.post("/send-email", async (req, res) => {
const { to, subject, text } = req.body;
try {
await axios.post("https://api.resend.com/emails", {
- from: "you@yourdomain.com",
to,
subject,
text
}, {
- headers: { Authorization:
Bearer ${process.env.RESEND_API_KEY}}
});
res.send("Email sent via API!");
} catch (err) {
res.status(500).send("Error sending email");
}
});
⚠️ Best Practices
Use environment variables (.env) for credentials.
Never expose API keys in client-side code.
Set up SPF/DKIM/DMARC for your domain to avoid spam folders.
Log and monitor delivery status with webhooks or dashboards.
✅ When to Choose What
-
Quick setup, small apps: Nodemailer with Gmail/Outlook.
-
Scalable, production-ready apps: API providers like Resend, Postmark, or SendGrid.
-
Cost-sensitive, high-volume apps: Amazon SES (requires more setup).