Event Webhook Python Code Example
(information)
Info
We recommend using our official Python SDK, our client library with full documentation, when integrating with SendGrid's Inbound Parse Webhook.
In this example, we want to parse all emails at address@email.sendgrid.biz
and post the parsed email to http://sendgrid.biz/parse
. In this example we will be using Python the Flask framework.
Given this scenario, the following are the parameters you would set at the Parse API settings page:
Hostname: email.sendgrid.biz
URL: http://sendgrid.biz/parse
To test this scenario, we sent an email to example@example.com
and created the following code:
1from flask import Flask, request2import simplejson3app = Flask(__name__)45@app.route('/parse', methods=['POST'])6def sendgrid_parser():7# Consume the entire email8envelope = simplejson.loads(request.form.get('envelope'))910# Get some header information11to_address = envelope['to'][0]12from_address = envelope['from']1314# Now, onto the body15text = request.form.get('text')16html = request.form.get('html')17subject = request.form.get('subject')1819# Process the attachements, if any20num_attachments = int(request.form.get('attachments', 0))21attachments = []22if num_attachments > 0:23for num in range(1, (num_attachments + 1)):24attachment = request.files.get(('attachment%d' % num))25attachments.append(attachment.read())26# attachment will have all the parameters expected in a Flask file upload2728return "OK"2930if __name__ == '__main__':31app.run(debug=True)32