Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created August 2, 2011 04:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pamelafox/1119632 to your computer and use it in GitHub Desktop.
Save pamelafox/1119632 to your computer and use it in GitHub Desktop.
Using SendGrid Incoming API with Python Flask
# Setup datastore model for storing mail
class ParsedMail(db.Model):
from_address = db.StringProperty()
to_address = db.StringProperty()
text = db.TextProperty()
subject = db.StringProperty()
# Set up URL handler for the incoming mail
app.add_url_rule('/hook/parse-mail', view_func=views.parse_mail, methods=['POST'])
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