Skip to content

Instantly share code, notes, and snippets.

@ocelotsloth
Created February 6, 2020 15:53
Show Gist options
  • Save ocelotsloth/872a69c6efa0206f83cdf6e12a6f52e5 to your computer and use it in GitHub Desktop.
Save ocelotsloth/872a69c6efa0206f83cdf6e12a6f52e5 to your computer and use it in GitHub Desktop.
Get Mailgun Bounce List
import requests
import csv
import datetime
#################################################################
# Configure mailgun domain and api key here
#################################################################
domain = "MAILGUN_DOMAIN_HERE"
apikey = "API_KEY_HERE"
#################################################################
abort = False
if domain == "MAILGUN_DOMAIN_HERE":
print("ERROR: You must configure the mailgun domain at the top of this script.")
abort = True
if apikey == "API_KEY_HERE":
print("ERROR: You must configure the mailgun api secret key at the top of this script.")
abort = True
if abort:
exit(1)
bounces = []
request_url = 'https://api.mailgun.net/v3/{0}/bounces'.format(domain)
while True:
print(request_url)
r = requests.get(request_url, auth=('api', apikey))
if r.status_code != 200:
print("error!")
break
r_json = r.json()
items = r_json['items']
if len(items) <= 0:
break
for bounce in items:
bounces.append(bounce)
request_url = r_json['paging']['next']
f = open("bounces-{0}.csv".format(datetime.datetime.now().isoformat()), "w", newline='')
writer = csv.writer(f)
writer.writerow(['MessageHash', 'address', 'code', 'created_at'])
for bounce in bounces:
writer.writerow([
bounce['MessageHash'],
bounce['address'],
bounce['code'],
bounce['created_at'],
])
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment