Prompt
How do I send emails from a backend?
Latest observation
Sep 23, 2026
OpenAI APIWeb search: off
To send emails from a backend, the usual approach is:
-
Choose an email provider
- SMTP service: Gmail SMTP, Office 365, your hosting provider, etc.
- Transactional email API: SendGrid, Mailgun, Amazon SES, Postmark, Resend, etc.
- For production, an email API is usually easier and more reliable than raw SMTP.
-
Use a backend library or SDK
- Most languages have libraries for SMTP or the provider’s API.
- Your backend should call the email service directly; the frontend should not send email itself.
-
Store credentials securely
- Put API keys or SMTP passwords in environment variables or a secrets manager.
- Never hardcode them in the codebase.
-
Build an email-sending function
- Inputs: recipient, subject, body, maybe HTML.
- Handle failures, retries, and logging.
-
Send asynchronously if possible
- For app emails like password resets, confirmations, receipts, etc., queue the send task so the request doesn’t block.
- Common tools: RabbitMQ, SQS, Celery, BullMQ, Sidekiq, etc.
-
Set up domain authentication
- Configure SPF, DKIM, and DMARC so messages are less likely to be marked as spam.
- Use a verified sending domain.
Example: Node.js with Nodemailer (SMTP)
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 587,
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
async function sendEmail(to, subject, text) {
await transporter.sendMail({
from: '"My App" <no-reply@myapp.com>',
to,
subject,
text,
});
}
sendEmail("user@example.com", "Welcome!", "Thanks for signing up.");
Example: SendGrid API
import sgMail from "@sendgrid/mail";
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
await sgMail.send({
to: "user@example.com",
from: "no-reply@myapp.com",
subject: "Welcome!",
text: "Thanks for signing up.",
});
Example: Python with smtplib
import smtplib
from email.message import EmailMessage
import os
msg = EmailMessage()
msg["Subject"] = "Welcome!"
msg["From"] = "no-reply@myapp.com"
msg["To"] = "user@example.com"
msg.set_content("Thanks for signing up.")
with smtplib.SMTP(os.environ["SMTP_HOST"], 587) as smtp:
smtp.starttls()
smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASS"])
smtp.send_message(msg)
Best practices
- Use a no-reply or dedicated sender address
- Include both plain text and HTML versions if possible
- Validate recipient addresses
- Add rate limiting to avoid abuse
- Log send results and failures
- Don’t send directly from the client/browser
- Use a queue for high-volume or critical emails
- Make sure you have user consent where required
If you tell me your backend stack (Node, Python, PHP, Java, .NET, etc.), I can give you a ready-to-use example.