Skip to contentSkip to navigationSkip to topbar
On this page

Event Webhook Python Code Example



Parse Webhook

parse-webhook page anchor
(information)

Info

We recommend using our official Python SDK, our client library with full documentation, when integrating with SendGrid's Inbound Parse Webhook(link takes you to an external page).

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(link takes you to an external 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:

1
from flask import Flask, request
2
import simplejson
3
app = Flask(__name__)
4
5
@app.route('/parse', methods=['POST'])
6
def sendgrid_parser():
7
# Consume the entire email
8
envelope = simplejson.loads(request.form.get('envelope'))
9
10
# Get some header information
11
to_address = envelope['to'][0]
12
from_address = envelope['from']
13
14
# Now, onto the body
15
text = request.form.get('text')
16
html = request.form.get('html')
17
subject = request.form.get('subject')
18
19
# Process the attachements, if any
20
num_attachments = int(request.form.get('attachments', 0))
21
attachments = []
22
if num_attachments > 0:
23
for num in range(1, (num_attachments + 1)):
24
attachment = request.files.get(('attachment%d' % num))
25
attachments.append(attachment.read())
26
# attachment will have all the parameters expected in a Flask file upload
27
28
return "OK"
29
30
if __name__ == '__main__':
31
app.run(debug=True)
32