Email Service Setup Guide: SendGrid & Mailgun Integration from Start to Expert
Reliable email delivery is essential infrastructure for any website — from registration confirmations to marketing campaigns. This guide covers configuration of two most popular email services: SendGrid and Mailgun.
Why Use a Professional Email Service?
Sending email from your own server has drawbacks:
- Low IP reputation, often marked as spam
- Strict delivery limits from Gmail/Outlook
- Complex Postfix/Dovecot maintenance
Professional services provide:
- High-reputation sending IP pools
- Complete SPF/DKIM/DMARC authentication
- Real-time delivery analytics
- Elastic scalability
Transactional vs. Marketing Email
Before configuring anything, it helps to separate the two kinds of email you will send, because they pull deliverability settings in different directions:
| Dimension | Transactional | Marketing |
|---|---|---|
| Examples | Signup verification, password reset, order notices | Promotions, newsletters, re-engagement |
| Time sensitivity | Minutes; must arrive before a code expires | Hours; some delay is tolerable |
| Unsubscribe | Not required | Required, one-click |
| Delivery strategy | Maximize reliability | Ramp gradually |
| Failure handling | Retry + alert, resend promptly | Fail silently, avoid spamming |
It is a good practice to use separate sending domains or subdomains (for example transaction.example.com and marketing.example.com) with their own SPF/DKIM records and IP reputation, so a marketing deliverability hiccup does not drag down transactional mail. Many teams also assign separate sender identities per product line, which makes it much easier to trace problems back to a specific business when something goes wrong.
Tracking Delivery with Webhooks
"Sending" is not the same as "delivered." Wire event callbacks back into your own system:
- Enable the Event Webhook in SendGrid and POST events such as
delivered,open,click,bounce, andspamreportto your endpoint. - Mailgun exposes
delivered,failed,opened, andclickedevents; configure a forwarding URL under Routes.
# Python/Flask handler for the SendGrid Event Webhook
from flask import Flask, request
app = Flask(__name__)
@app.post('/webhook/sendgrid')
def sendgrid_webhook():
for event in request.get_json():
if event['event'] == 'bounce':
log_bounce(event['email'], event.get('reason', ''))
if event['event'] == 'spamreport':
mark_spam(event['email'])
return 'ok'
Watch three metrics: bounce rate (above 2% means check DNS and list quality), open rate (a sudden drop usually means spam folder), and spam complaint rate (above 0.1% can get you rate-limited). Export the data weekly to compare trends and surface anomalies early.
A First-Week Launch Checklist
For a brand-new site, following this order avoids most "email never arrives" problems:
- Day 1: register SendGrid/Mailgun, verify your domain, and send the first test message.
- Day 2: test with three to five different mailboxes (Gmail, Outlook, QQ Mail, a corporate account) and confirm nothing lands in spam.
- Day 3: wire up templates and webhooks, logging bounces and complaints.
- Days 4-7: watch delivery and open rates; if needed, request a dedicated IP and start IP warm-up.
- Before launch: move DMARC from
p=nonetop=quarantine.
IP warm-up is easy to overlook: a freshly assigned dedicated IP starts with low reputation, so you should ramp from a few hundred messages a day and build up gradually. Jumping straight to high volume is a fast way to get blocked by the big mailboxes.
Reference: SendGrid docs https://docs.sendgrid.com/, Mailgun docs https://documentation.mailgun.com/, RFC 7489 (DMARC) https://datatracker.ietf.org/doc/html/rfc7489
1. SendGrid Setup
Registration & API Key
- Visit SendGrid and register
- Free tier: 100 emails/day (permanent, ideal for small sites)
- Settings → API Keys → Create API Key (Full Access)
SMTP Config
SENDGRID_API_KEY=SG.xxxxxxxxxxxxxxxxxxxx
[email protected]
SENDGRID_FROM_NAME=Your Site Name
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: '[email protected]',
from: { email: process.env.SENDGRID_FROM_EMAIL, name: process.env.SENDGRID_FROM_NAME },
subject: 'Welcome!',
text: 'Thank you for registering...',
html: '<p>Thank you for registering...</p>',
};
sgMail.send(msg);
Domain Authentication
Add the following DNS records in SendGrid Dashboard → Settings → Sender Authentication:
# SPF
v=spf1 include:sendgrid.net ~all
# DKIM - CNAME records provided by SendGrid
# Domain verification - CNAME record
2. Mailgun Setup
Registration
- Visit Mailgun and register
- Free tier: first 3 months 5000/month, then 1000/month
- Add your sending domain in Domains page
API Sending
import requests
def send_email(to, subject, html):
return requests.post(
f"https://api.mailgun.net/v3/{YOUR_DOMAIN}/messages",
auth=("api", MAILGUN_API_KEY),
data={
"from": f"Your Site <noreply@{YOUR_DOMAIN}>",
"to": [to],
"subject": subject,
"html": html
})
DNS Records
TXT @ v=spf1 include:mailgun.org ~all
TXT xxxxx._domainkey k=rsa; p=MIGfMA0GCSqGSIb3...
MX mxa.mailgun.org 10
MX mxb.mailgun.org 10
3. SPF, DKIM, DMARC Setup
SPF
Declares authorized sending servers:
v=spf1 include:sendgrid.net include:mailgun.org ~all
DKIM
Digital signature to verify email integrity:
[selector]._domainkey.[domain] TXT "v=DKIM1; k=rsa; p=[public_key]"
DMARC
Policy for unauthenticated emails:
_dmarc.[domain] TXT "v=DMARC1; p=quarantine; rua=mailto:[email protected]"
DMARC policies: p=none (monitor) → p=quarantine (spam) → p=reject (reject)
4. SendGrid vs Mailgun
| Aspect | SendGrid | Mailgun |
|---|---|---|
| Free tier | 100/day | 1000/month |
| Overage (50K) | $19.95/month | $35/month |
| Delivery rate | High | Very high |
| Analytics | Rich | Basic |
| Templates | Dynamic templates | Template variables |
5. Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| Emails in spam | SPF/DKIM misconfigured | Check DNS records |
| SMTP timeout | Firewall blocked | Use port 587 (TLS) |
| Sending rejected | Low reputation/quota | Warm up IP, check limits |
| Low open rate | Unengaging subject | A/B test subject lines |
16IDC Takeaway
For most small to medium websites, start with SendGrid's free tier (100 emails/day covers early needs). When delivery requirements grow, consider Mailgun. Configure SPF, DKIM and DMARC before going live — this is the single most important step for email deliverability.