Skip to content

Instantly share code, notes, and snippets.

@ocelotsloth
Created February 6, 2020 15:53
Show Gist options
  • Select an option

  • Save ocelotsloth/872a69c6efa0206f83cdf6e12a6f52e5 to your computer and use it in GitHub Desktop.

Select an option

Save ocelotsloth/872a69c6efa0206f83cdf6e12a6f52e5 to your computer and use it in GitHub Desktop.

Revisions

  1. ocelotsloth created this gist Feb 6, 2020.
    53 changes: 53 additions & 0 deletions mailgun-bounces.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    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()