Created
August 2, 2011 04:58
-
-
Save pamelafox/1119632 to your computer and use it in GitHub Desktop.
Using SendGrid Incoming API with Python Flask
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
# Setup datastore model for storing mail | |
class ParsedMail(db.Model): | |
from_address = db.StringProperty() | |
to_address = db.StringProperty() | |
text = db.TextProperty() | |
subject = db.StringProperty() |
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
# Set up URL handler for the incoming mail | |
app.add_url_rule('/hook/parse-mail', view_func=views.parse_mail, methods=['POST']) |
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
def parse_mail(): | |
envelope = simplejson.loads(request.form.get('envelope')) | |
to_address = envelope['to'][0] | |
from_address = envelope['from'] | |
text = request.form.get('text') | |
subject = request.form.get('subject') | |
# Save to datastore | |
parsed_mail = ParsedMail(to_address=to_address, from_address=from_address, subject=subject, text=text) | |
parsed_mail.save() | |
# Reading attachments into a list | |
attachments = [] | |
num_attachments = int(request.form.get('attachments', 0)) | |
if num_attachments > 0: | |
for num in range(1, (num_attachments + 1)): | |
attachment = request.files.get(('attachment%d' % num)) | |
attachments.append(attachment.read()) | |
# Do stuff with attachments and mail. Your call. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment