Skip to content

Instantly share code, notes, and snippets.

@ChrisButterworth
Created March 24, 2017 10:18
Show Gist options
  • Save ChrisButterworth/d7acab0fce3a70f17dbcfdb3eacebb98 to your computer and use it in GitHub Desktop.
Save ChrisButterworth/d7acab0fce3a70f17dbcfdb3eacebb98 to your computer and use it in GitHub Desktop.
MailGun message download
# This Python file uses the following encoding: utf-8
"""View a message using it’s Mailgun storage key."""
import os
import sys
import uuid
import requests
def r_string(string_length=10):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-","") # Remove the UUID '-'.
return random[0:string_length] # Return the random string.
if len(sys.argv) != 3:
print "Usage: retrieve.py sub_domain message_key"
sys.exit(1)
# keep it in secret!
api_key = "key-suppliedbymailgin"
path = os.getcwd()+"/"+r_string()
# output file name

file_name = path+"/message.eml"
# let's make the url for retrieval
domain = "example.com"
sub = sys.argv[1]
key = sys.argv[2]
url = "https://%s.api.mailgun.net/v3/domains/%s/messages/%s"
url = url % (sub, domain, key)
# this will help us to get the raw MIME
headers = {"Accept": "message/rfc2822"}
# let's make a request to the API
r = requests.get(url, auth=("api", api_key), headers=headers)
if r.status_code == 200:
# dump the body to a file
os.mkdir(path);
with open(file_name, "w") as message:
message.write(r.json()["body-mime"].encode('utf-8'))
# open it in the bird
# os.system("/Applications/Thunderbird.app/Contents/MacOS/thunderbird-bin -file %s" % file_name)
else:
print "Oops! Something went wrong: %s" % r.content
@ChrisButterworth
Copy link
Author

Usage
python retreive.py sub message_key

Needs API key from MailGun

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment