SendGrid Email Categories: Organize, Filter & Analyze Email Streams
In this tutorial, you will learn about SendGrid Email Categories: Organize, Filter & Analyze Email Streams. We cover key concepts, practical examples, and best practices to help you master this topic.
SendGrid categories tag emails with custom labels, enabling you to filter analytics reports, track deliverability per category, and organize your email streams by purpose.
What You'll Learn
How to add categories to emails, use categories for analytics filtering, track deliverability per email type, and organize email streams for better monitoring.
Why It Matters
Without categories, all emails blend together in analytics. With categories, you can see: "Welcome emails have 98% delivery but alert emails have 92% — investigate the alert stream." DodaTech categorizes emails by type and monitors each stream separately.
Real-World Use
A developer adds category "weekly-report" to all report emails. In analytics, they filter by category and discover that report emails to @outlook.com addresses have higher bounce rates.
flowchart LR
A["Send Email\n+ Category Tag"] --> B["SendGrid\nProcess"]
B --> C["Analytics\nFilter by Category"]
C --> D["Welcome\n98% Delivery"]
C --> E["Alerts\n92% Delivery"]
C --> F["Reports\n99% Delivery"]
D --> G["Investigate\nAlert Stream"]
style A fill:#dbeafe,stroke:#2563eb
style C fill:#fef3c7,stroke:#d97706
style G fill:#fecaca,stroke:#dc2626
Adding Categories
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Category
def send_with_category(to_email, subject, body, category_name):
message = Mail(
from_email="noreply@dodatech.com",
to_emails=to_email,
subject=subject,
html_content=body
)
message.add_category(Category(category_name))
response = sg.send(message)
print(f"Email sent with category '{category_name}': {response.status_code}")
send_with_category(
"alice@example.com",
"Welcome to DodaTech",
"<h1>Welcome!</h1>",
"welcome-email"
)
# Expected output: Email sent with category 'welcome-email': 202
Multiple Categories
def send_with_multiple_categories(to_email, subject, body, categories):
message = Mail(
from_email="reports@dodatech.com",
to_emails=to_email,
subject=subject,
html_content=body
)
for cat in categories:
message.add_category(Category(cat))
response = sg.send(message)
print(f"Email with categories {categories}: {response.status_code}")
send_with_multiple_categories(
"bob@example.com",
"Weekly Security Report",
"<h1>Your Report</h1>",
["weekly-report", "transactional", "user-bob"]
)
# Expected output: Email with categories ['weekly-report', 'transactional', 'user-bob']: 202
Category Analytics
from sendgrid import SendGridAPIClient
from datetime import datetime, timedelta
def get_category_stats(category, days=7):
now = datetime.now()
start = now - timedelta(days=days)
params = {
"start_date": start.strftime("%Y-%m-%d"),
"end_date": now.strftime("%Y-%m-%d"),
"aggregated_by": "day",
"categories": category
}
response = sg.client.stats.get(query_params=params)
stats = response.to_dict()
print(f"Statistics for category '{category}' (last {days} days):")
total_delivered = 0
total_opens = 0
total_bounces = 0
for day in stats:
metrics = day.get("stats", [{}])[0].get("metrics", {})
total_delivered += metrics.get("delivered", 0)
total_opens += metrics.get("unique_opens", 0)
total_bounces += metrics.get("bounces", 0)
print(f" Delivered: {total_delivered}")
print(f" Opens: {total_opens}")
print(f" Bounces: {total_bounces}")
return stats
get_category_stats("welcome-email")
# Expected output:
# Statistics for category 'welcome-email' (last 7 days):
# Delivered: 4520
# Opens: 1830
# Bounces: 23
Category Analytics with Multiple
def compare_categories(categories, days=30):
print(f"{'Category':<20} {'Sent':<10} {'Delivered':<12} {'Opens':<10} {'Bounce%':<10}")
print("-" * 62)
for cat in categories:
params = {
"start_date": (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d"),
"end_date": datetime.now().strftime("%Y-%m-%d"),
"aggregated_by": "day",
"categories": cat
}
response = sg.client.stats.get(query_params=params)
stats = response.to_dict()
sent = sum(s.get("stats", [{}])[0].get("metrics", {}).get("requests", 0) for s in stats)
delivered = sum(s.get("stats", [{}])[0].get("metrics", {}).get("delivered", 0) for s in stats)
opens = sum(s.get("stats", [{}])[0].get("metrics", {}).get("unique_opens", 0) for s in stats)
bounces = sum(s.get("stats", [{}])[0].get("metrics", {}).get("bounces", 0) for s in stats)
bounce_rate = (bounces / max(sent, 1)) * 100
print(f"{cat:<20} {sent:<10} {delivered:<12} {opens:<10} {bounce_rate:.1f}%")
compare_categories(["welcome-email", "password-reset", "weekly-report", "alert"])
Common Mistakes
1. Using Too Many Categories
Each email can have up to 10 categories. Too many categories dilute analytics. Use 3-5 meaningful categories per email.
2. Inconsistent Category Names
"welcome-email" and "welcome_email" are different categories. Standardize naming conventions: use lowercase with hyphens.
3. Not Using Categories at All
Without categories, all analytics are aggregated. You can't tell whether welcome emails perform differently from alerts.
4. Category Typos
A typo in the category name creates a new, empty category in analytics. Use constants or enums for category names.
5. Including User-Specific Data in Categories
Categories like "user-alice" create thousands of categories, making analytics useless. Use custom arguments for per-user tracking, categories for email-type tracking.
Practice Questions
- What are SendGrid categories used for?
- How many categories can you add per email?
- How do you retrieve category-specific analytics?
- What should you not use categories for?
Answers:
- Categories tag emails by type or purpose for filtering analytics and tracking deliverability per email stream.
- Up to 10 categories per email.
- Use the Stats API with the
categoriesquery parameter to filter analytics by one or more categories. - Don't use categories for user-specific tracking (thousands of categories are unmanageable). Use custom arguments for per-user data.
Challenge: Implement a category system for Durga Antivirus Pro emails: define categories for welcome, password-reset, weekly-report, alert, and invoice. Send test emails with each category, then retrieve per-category analytics and identify the stream with the lowest deliverability.
FAQ
Mini Project
Build a category analytics dashboard: define categories for all email types, implement category tagging in the send function, retrieve per-category stats via Stats API, and create a comparison report showing deliverability, open rates, and bounce rates per category.
What's Next
Suppression Groups — manage unsubscribe preferences and Compliance.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro