Prompt
How do I send emails from a REST API?
Latest observation
Sep 23, 2026
OpenAI APIWeb search: off
To send emails from a REST API, your API usually does not send the email itself directly. Instead, it calls an email provider (like SendGrid, Mailgun, Amazon SES, Postmark, etc.) or uses your own SMTP server.
Common approach
1. Create an endpoint in your API
For example:
POST /send-email
Request body:
{
"to": "user@example.com",
"subject": "Welcome!",
"body": "Thanks for signing up."
}
2. Validate the request
Check things like:
- valid email address
- subject/body not empty
- authenticated user
- rate limiting / spam protection
3. Send via an email service
Your backend then either:
- calls the provider’s HTTP API, or
- uses SMTP credentials to send mail
Example: Using a provider API
Node.js example with SendGrid
import sgMail from "@sendgrid/mail";
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
app.post("/send-email", async (req, res) => {
const { to, subject, body } = req.body;
try {
await sgMail.send({
to,
from: "no-reply@yourdomain.com",
subject,
text: body,
});
res.status(200).json({ message: "Email sent" });
} catch (err) {
res.status(500).json({ error: "Failed to send email" });
}
});
Example: Using SMTP
If you have an SMTP server:
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({
host: "smtp.example.com",
port: 587,
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
app.post("/send-email", async (req, res) => {
const { to, subject, body } = req.body;
try {
await transporter.sendMail({
from: "no-reply@yourdomain.com",
to,
subject,
text: body
});
res.json({ message: "Email sent" });
} catch (err) {
res.status(500).json({ error: "Failed to send email" });
}
});
Best practices
- Use a trusted email provider
- Don’t expose SMTP/API keys in frontend code
- Queue emails for high traffic
- Use templates for consistent formatting
- Add retry logic and logging
- Authenticate the API endpoint
- Prevent abuse/spam
If you’re building the REST API itself
A typical flow is:
- Client calls your API:
POST /emails - Your API validates the request
- Your API sends the email via provider
- Your API returns success/failure
If you want, I can show you how to do this in Python (Flask/FastAPI), Node.js (Express/NestJS), or Java/Spring Boot.