Skip to content

Instantly share code, notes, and snippets.

@nilstoedtmann
Created April 21, 2020 19:46
Show Gist options
  • Save nilstoedtmann/f5d38abf9f2f9de50525fcefa951437e to your computer and use it in GitHub Desktop.
Save nilstoedtmann/f5d38abf9f2f9de50525fcefa951437e to your computer and use it in GitHub Desktop.
Retrieve and parse MailGun bounces & suppressions via MailGun API
#!/usr/bin/env python
'''Retrieve and parse MailGun bounces & suppressions via MailGun API.
Set MAILGUN_API_KEY and MAILGUN_DOMAIN as env vars.
See https://documentation.mailgun.com/en/latest/api-suppressions.html#view-all-bounces
'''
import os, sys, json, logging, requests, datetime
__copyright__ = "Copyright (c) 2020, Demand Logic Limited. All rights reserved."
__author__ = "Nils Toedtmann <nils.toedtmann@demandlogic.co.uk>"
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
try:
mailgun_domain = sys.argv[1]
except IndexError:
mailgun_domain = os.environ['MAILGUN_DOMAIN']
mailgun_api_key = os.environ['MAILGUN_API_KEY']
auth = ("api", mailgun_api_key)
item_list = []
next_url = "https://api.mailgun.net/v3/{}/bounces".format(mailgun_domain)
while next_url:
result = requests.get(next_url, auth=auth)
log.info("Status code={}, reason='{}'".format(result.status_code, result.reason))
if result.status_code != 200:
sys.exit(1)
c = json.loads(result.text)
item_list += c['items']
first_url = c['paging'].get('first', None)
next_url = c['paging'].get('next', None)
if first_url == next_url:
next_url = None
log.info("Found %s items", len(item_list))
bounces = {}
for item in item_list:
address = item['address']
domain = address.split('@')[1]
# Date format: 'Fri, 20 Jan 2017 11:02:07 UTC'
date = item['created_at']
date = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S UTC')
date = date.date()
# Strip NewLines
error = item['error']
error = '_'.join(error.split('\n'))
if not domain in bounces:
bounces[domain] = {}
bounces[domain][address] = "[{}] {}".format(date, error)
json.dump(bounces, sys.stdout, indent=4, sort_keys=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment