Skip to content

Instantly share code, notes, and snippets.

@ewandennis
Created November 17, 2016 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewandennis/4af0c7fc7329ff14fde6a387fc92043f to your computer and use it in GitHub Desktop.
Save ewandennis/4af0c7fc7329ff14fde6a387fc92043f to your computer and use it in GitHub Desktop.
SparkPost relay webhooks sample
"""Receive an extract email attachments using SparkPost relay webhooks.
Prerequisites:
- An inbound domain: https://developers.sparkpost.com/api/inbound-domains.html
- A relay webhook: https://developers.sparkpost.com/api/relay-webhooks.html
Dependencies:
- flask
"""
from flask import Flask, request
from base64 import b64decode
from email import message_from_string
app = Flask(__name__)
@app.route('/', methods=['POST'])
def receive_messages():
messages = request.get_json(silent=True)
for msg in messages:
content = msg['msys']['relay_message']['content']
body = content['email_rfc822']
if content['email_rfc822_is_base64']:
body = b64decode(body)
email = message_from_string(body)
first_text = False
first_html = False
for part in email.walk():
if part.get_content_maintype() == 'multipart':
continue
if not first_text and part.get_content_type() == 'text/plain':
first_text = True
continue
if not first_html and part.get_content_type() == 'text/html':
first_html = True
continue
with open(part.get_filename(), 'wb') as fp:
fp.write(part.get_payload(decode=True))
print('Filename: %s' % part.get_filename())
return 'Received %d message(s)' % len(messages)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment