Prompt
how to send emails from backend code
Latest observation
Nov 8, 2026
OpenAI APIWeb search: off
To send emails from backend code, you generally use an SMTP server or a third-party email API.
Common approaches
1) Use an email service provider
Examples: SendGrid, Mailgun, Amazon SES, Postmark, Resend
This is usually the easiest and most reliable option for production.
Typical steps:
- Create an account with the provider.
- Verify your domain.
- Get API keys or SMTP credentials.
- Install their SDK or use SMTP from your backend.
- Send email from your server code.
2) Use SMTP directly
You can connect to an SMTP server from your backend using libraries in your language.
Example concept:
- host:
smtp.gmail.comor provider SMTP host - port:
587or465 - username/password or app password
- send mail via a mail library
Example: Node.js with Nodemailer
const nodemailer = require('nodemailer');
async function sendEmail() {
let transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: 'your-email@example.com',
pass: 'your-password'
}
});
let info = await transporter.sendMail({
from: '"My App" <your-email@example.com>',
to: 'user@example.com',
subject: 'Hello',
text: 'This is a test email',
html: '<b>This is a test email</b>'
});
console.log('Message sent:', info.messageId);
}
sendEmail().catch(console.error);
Example: Python with smtplib
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("This is a test email")
msg["Subject"] = "Hello"
msg["From"] = "your-email@example.com"
msg["To"] = "user@example.com"
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("your-email@example.com", "your-password")
server.send_message(msg)
print("Email sent")
Important best practices
- Never hardcode credentials in source code.
- Store secrets in environment variables.
- Use app passwords if using Gmail/Outlook.
- Configure SPF, DKIM, and DMARC for better deliverability.
- Consider using a queue/background job if sending many emails.
- Always validate user input to prevent abuse.
Which method should you choose?
- Small project / testing: SMTP or a simple API provider
- Production app: Email API provider like SendGrid, SES, Postmark, or Resend
If you want, I can show you how to send emails in your backend language (Node.js, Python, Java, PHP, Go, C#, etc.).