Skip to content

Instantly share code, notes, and snippets.

@gaieges
Last active December 14, 2023 18:04
Show Gist options
  • Save gaieges/a815e78e5b31b16a38c9aba62a6c5a59 to your computer and use it in GitHub Desktop.
Save gaieges/a815e78e5b31b16a38c9aba62a6c5a59 to your computer and use it in GitHub Desktop.
Parse'ing Sendgrid inbound messages via webhook in python and fastapi

Sendgrid inbound parse'ing in python and fastapi

This took me far too long to figure out how to parse emails coming in from sendgrid's "inbound parse" tool to receive an email via webhook, so I saved it for others to view if they stumble upon it.

The key to this is to check off the setting "POST the raw, full MIME message" in the inbound parse webhook address options.

import logging
from fastapi import Form, FastAPI
from email import message_from_string
app = FastAPI()
LOG = logging.getLogger()
@app.post("/sendgrid-inbound-parse")
async def parse_sendgrid_email(email: str = Form()):
message = message_from_string(email)
subject = message.get('subject')
from_ = message.get('from')
body = ""
if message.is_multipart():
for part in message.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# skip any text/plain (txt) attachments
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True).decode()
break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
body = message.get_payload(decode=True).decode()
LOG.info(f'{subject=} {from_=} {body=}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment