Created
November 17, 2016 15:54
-
-
Save ewandennis/4af0c7fc7329ff14fde6a387fc92043f to your computer and use it in GitHub Desktop.
SparkPost relay webhooks sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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