Why Your Emails Are Landing in Spam: Automating Sending-Domain Health Checks
Last month, one of our critical automated alerting services silently reached zero users because a single DNS record expired during a routine infrastructure migration. We didn't notice until customer support flooded our Slack channels with frantic messages about password resets vanishing into the ether. That painful wake-up call forced me to build a robust, scheduled monitoring pipeline for our sending-domain health.
The Problem Everyone Ignores
Most engineering teams treat email infrastructure like a set-and-forget utility. We configure our SPF, DKIM, and DMARC records once during initial product setup, celebrate the green checkmarks in our DNS dashboard, and never look at them again.
But the internet changes under your feet. DNS providers experience caching glitches, domain registrars drop records during auto-renewals, and mailbox providers like Gmail and Microsoft tighten their spam filters daily. If you aren't actively tracking your mail status metrics and DNS hygiene, your domain reputation is slowly bleeding out.
I learned this the hard way after watching our email deliverability plummet from 98% down to a miserable 12% over a single weekend. A misconfigured CNAME for our custom return-path broke our cryptographic signatures, turning every transactional email we sent into an immediate red flag for receiving servers.
By the time automated internal alarms finally triggered, our domain was already flagged on multiple blacklists. Recovering that sender reputation took weeks of manual warm-up procedures, support tickets, and carrier appeals that could have been entirely avoided with proactive monitoring.
What Actually Works
To fix this permanently, we need a proactive strategy that continuously checks both sides of the email delivery equation: cryptographic DNS configurations and actual mailbox delivery status metrics. Waiting for a user complaint is a failure state that costs real revenue and user trust.
The architecture that finally solved this for us is a scheduled cron job combined with a lightweight Python worker that queries DNS records via dnspython and polls our email service provider API for bounce rates and spam complaints. It evaluates these data points against strict thresholds and fires an immediate webhook to PagerDuty if anything looks fishy.
It works because it decouples email monitoring from application logic. Even if your core web service is running fine, this background sentinel runs independently every hour to verify that your domain's cryptographic armor is fully intact and your reputation metrics remain pristine.
Let's look at a complete script that handles the DNS verification layer for SPF, DKIM, and DMARC, checking records against expected values and flagging anomalies before they impact your business.
import dns.resolver
import sys
def verify_domain_records(domain, expected_dmarc):
resolver = dns.resolver.Resolver()
results = {"spf": False, "dkim": False, "dmarc": False}
try:
txt_records = resolver.resolve(domain, 'TXT')
for rdata in txt_records:
txt = rdata.to_text().strip('"')
if "v=spf1" in txt:
results["spf"] = True
except Exception as e:
print(f"SPF Check Failed: {e}")
try:
dmarc_domain = f"_dmarc.{domain}"
dmarc_records = resolver.resolve(dmarc_domain, 'TXT')
for rdata in dmarc_records:
txt = rdata.to_text().strip('"')
if expected_dmarc in txt:
results["dmarc"] = True
except Exception as e:
print(f"DMARC Check Failed: {e}")
return results
if __name__ == "__main__":
status = verify_domain_records("example.com", "v=DMARC1;")
print(f"Domain Health Status: {status}")
This script uses the standard dns.resolver module to query your domain's public DNS zone for valid SPF strings and DMARC enforcement policies, returning a clear boolean dictionary of your current cryptographic standing.
Step-by-Step: Let's Build It Together
Building a production-grade monitoring pipeline requires two distinct phases: first, setting up automated DNS validation for cryptographic keys, and second, integrating mailbox telemetry metrics from your email provider API. Let's break down the implementation into concrete, runnable blocks.
For Step 1, we write a robust wrapper function that handles multiple DKIM selectors across different mailing services, ensuring you never miss a rotated key or an accidental deletion in your DNS management dashboard.
import dns.resolver
def check_dkim_selectors(domain, selectors):
resolver = dns.resolver.Resolver()
health_report = {}
for selector in selectors:
query_target = f"{selector}._domainkey.{domain}"
try:
answers = resolver.resolve(query_target, 'CNAME')
health_report[selector] = "Valid CNAME"
except dns.resolver.NoAnswer:
try:
answers = resolver.resolve(query_target, 'TXT')
health_report[selector] = "Valid TXT"
except Exception:
health_report[selector] = "Missing or Broken"
except Exception as e:
health_report[selector] = f"Error: {str(e)}"
return health_report
if __name__ == "__main__":
selectors = ["resend", "sendgrid", "mailjet"]
report = check_dkim_selectors("example.com", selectors)
print(report)
We successfully iterated through a list of common email provider selectors to verify that your DKIM cryptographic records resolve correctly as either TXT or CNAME entries.
For Step 2, we need to tie our DNS checker together with a metrics fetcher that calls an external email provider API to look at hard bounce rates and spam complaint thresholds over a sliding 24-hour window.
import requests
import os
def fetch_mail_metrics(api_key):
url = "https://api.emailprovider.v1/metrics/summary"
headers = {"Authorization": f"Bearer {api_key}"}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
bounce_rate = data.get("bounce_rate", 0.0)
complaint_rate = data.get("complaint_rate", 0.0)
return {"bounce_rate": bounce_rate, "complaint_rate": complaint_rate}
except requests.exceptions.RequestException as e:
print(f"Metrics API Error: {e}")
return None
if __name__ == "__main__":
metrics = fetch_mail_metrics(os.getenv("EMAIL_API_KEY", "dummy_key"))
print(f"Retrieved Metrics: {metrics}")
We queried the mail provider API with secure environment variables to pull real-time bounce and complaint telemetry needed for complete domain health analysis.
The Mistakes That Will Burn You
When engineers first tackle domain health monitoring, they often fall into classic traps that result in false alarms, brittle code, or missed security vulnerabilities. Here are the three most dangerous anti-patterns I see in production systems.
Avoid these pitfalls to ensure your monitoring infrastructure remains a reliable asset rather than another source of alert fatigue.
Let's examine how each of these mistakes plays out in real-world engineering environments so you can sidestep them entirely during your own implementation.
- Mistake 1: Hardcoding DNS nameservers and TTL values. If your primary nameserver provider experiences an outage or you migrate your DNS zone, your monitoring script will throw cascading false positives and flood your engineering channels with panic alerts.
- Mistake 2: Ignoring transient DNS resolution errors. Network packets drop and DNS lookups occasionally time out; if your script immediately fires a critical alert on a single failed query instead of implementing exponential backoff retries, you'll chase non-existent ghosts.
- Mistake 3: Monitoring only DNS records while ignoring actual mailbox metrics. Your SPF and DMARC records might look pristine on paper, but if your recipient complaint rate spikes due to poor list hygiene, mailbox providers will still silently block your traffic.
Production Checklist
Before you merge your monitoring code into main and deploy it to your Kubernetes cluster or serverless cron runner, make sure you have verified every item on this operational checklist.
Running a quick dry-run of your alerts in a staging environment will save you from late-night pager interruptions caused by misconfigured environment keys or overly aggressive thresholds.
Double-check your timeout configurations and API rate limits to ensure your monitoring script behaves nicely alongside your core application traffic.
- Do this: Set up exponential backoff retries for all DNS queries to handle intermittent network drops gracefully.
- Do this: Configure tiered alerting channels so minor DNS warnings go to Slack while hard delivery failures trigger PagerDuty.
- Never do this: Run monitoring scripts synchronously inside your core user request-response cycle where they can block threads or add latency.
Key Takeaways
Keeping your sending-domain health pristine requires a combination of automated cryptographic verification and continuous delivery telemetry.
By moving away from manual spot-checks and implementing scheduled background monitors, you protect your company's revenue and brand reputation.
- Automate hourly checks for SPF, DKIM, and DMARC configurations using robust DNS resolution libraries.
- Combine infrastructure checks with mailbox metrics like hard bounces and spam complaints for a holistic health score.
- Prevent alert fatigue by implementing smart retry logic and clear severity thresholds before shipping to production.
Engr. Hamza | AI & MLOps Engineer | Building autonomous systems at the edge of possibility

Top comments (0)