Technical document

Designing a System to Convert Incoming Emails into Business Data with SendGrid Inbound Parse

This article explains how to design a system that receives emails via Webhook, saves the original, and then converts it into business data. It covers signature verification, asynchronous parsing, handling retries, associating replies, and securely displaying content.
Email Integration / Data Design~12 minPublication Date September 22, 2026Update date September 22, 2026
Illustration showing the flow of saving emails to an original storage and converting them into organized data

Summary

Key points of this document

  • Inbound Parse: The Entry Point for Delivering Incoming Emails to a Webhook
  • Keep your usual inbox and add a dedicated path for ingestion
  • Perform signature verification before parsing multipart data

Overview

To handle email bodies and attachments within an application, it's essential to separate the entry point for receiving emails from the exit point for returning data used in business operations. SendGrid Inbound Parse serves as this entry point. Based on its public specifications, this article describes a design example that preserves the original email and allows re-parsing even after failures. This is not an article reporting the completion of a specific system implementation or measured performance.

Inbound Parse: The Entry Point for Delivering Incoming Emails to a Webhook

Inbound Parse is a feature that HTTP POSTs the content of emails received at a configured inbound host to a specified URL. This differs from methods where an application queries SendGrid to retrieve a list of incoming emails. A successful response to the Webhook indicates acceptance, but parsing results are not returned to the email sender.

In the normal parsing format, you can receive the subject, sender, recipient, text body, HTML body, headers, delivery recipient information, and attachments. Since it handles multipart/form-data including attachments, the starting point is not to implement the receiving process solely with request.json().

In raw mode, you can choose a configuration that receives the complete MIME message in the email field. Since the items received differ between normal and raw formats, we do not assume that both body and attachment fields are always present. In the design example in this article, which prioritizes verifying the original text and future re-parsing, raw mode is selected, and MIME is parsed after saving.

Keep your usual inbox and add a dedicated path for ingestion

Point the MX record of your inbound subdomain to SendGrid and register the same hostname and Webhook URL with Inbound Parse. If you want to maintain your everyday inbox, just add an ingestion subdomain and forward necessary emails to it. There's no need to replace the MX records for your entire existing inbound domain.

Transmission records can also be saved by Bcc'ing to a dedicated ingestion address. However, this record is a copy of the sent email and not proof of delivery or opening to the recipient. The design should determine the direction from the registration information of the inbound path and sending address, and not treat it as sent merely by the 'From' display. It's also possible to use a separate service for email sending functionality.

Separate inbound hosts, Webhooks, and storage destinations for production and validation environments. Before changing forwarding settings, check for any circular forwarding from existing destinations back to the ingestion destination, and initially confirm delivery with synthetic emails.

Perform signature verification before parsing multipart data

Inbound Parse has a security policy for configuring signature verification and OAuth. If using a signature method, not only create the policy but also associate it with the target Webhook and place the issued public key on the receiving side. Simply exposing the URL does not authenticate requests.

Use the HTTP body as received for signature verification. If you decompose multipart data first and then reassemble files or line breaks, the byte sequence will change, leading to verification failure. Verify the signature header and timestamp using the official method, and then proceed with content parsing.

Webhook signature verification proves communication with the sender. It does not prove that the original email sender is authentic or that they have permission to view/update a case. Email authentication results, participants, and ingestion path checks are performed separately. Replay protection is also necessary, but verify the handling of timestamps and behavior during retries to avoid rejecting legitimate re-transmissions.

Return success after saving the original and the reception ledger

The example configuration is: SendGrid → Reception Worker → Private R2 and D1 Reception Ledger → Queues → Parsing Worker → Viewing API. The Reception Worker performs size limits and signature verification, and saves the received original to a private area. D1 stores references to the original, processing status, retry information, and records awaiting queue submission.

Saving to R2, updating D1, and sending to Queues cannot be done in a single transaction. Therefore, after saving to R2, the reception ledger and pending submission records are committed in a single transaction within D1. A 2xx response is returned only after this is successful. The condition is that even if processing stops before queue submission, a periodic process can pick up pending submission records and recover.

If D1 saving fails after R2 saving, do not return success and prepare for re-delivery. Remaining unreferenced objects will be reconciled after matching with reception records and retention periods. If processing stops immediately after queue submission but before updating the submitted record, duplicate submissions can occur, so the parsing side needs a mechanism to avoid processing the same item multiple times.

SendGrid's official documentation states that 2xx stops re-delivery, 5xx triggers retries, and undeliverable emails are discarded after 3 days. Do not rely solely on external service retries for recovery; prepare monitoring to detect reception failures and a path to re-execute saved jobs.

  • Temporary failure before saving: Request retry with 5xx and monitor failure rate.
  • Parsing failure after saving: Retain the original, record retry count and failure code in the reception ledger.
  • Missed queue submission: Periodically scan pending submission records. Recover jobs that are stuck in processing with time-limited locks.
  • Retry limit: Move to quarantine or Dead Letter Queue, and have a human investigate the cause and re-submit.

Keep original, parsing results, and business affiliation separate

The original is the basis for verifying the source of the saved MIME and attachments. Parsing results are data generated from it for search and display, so they can be regenerated after parser modifications. Affiliation with a case is kept separately as business information that can be changed by a person. With this boundary, changing case assignments does not alter the original text or sender/recipient.

The JSON below is an example response from an acquisition API designed on the application side. It is not the SendGrid payload itself. An API that verifies authentication and viewing permissions returns it, and the body and attachments are retrieved on the necessary screen. The status is explicitly stated to avoid confusing an unparsed state with an empty body.

  • receivedAt: Timestamp recorded by the receiving infrastructure. messageDate: Date/time specified in the email. If Date is unparseable, set to null and retain the original text.
  • Message-ID, In-Reply-To, References: Save original headers and maintain separate parsed values for search.
  • Envelope recipient and To/Cc in headers: Distinguish between delivery destination and display destination. The Bcc ingestion destination may not necessarily be in To.
  • Attachments: Retain original reference, filename, declared MIME type, inspection results, and size, and do not make the storage location a public URL.
  • Case affiliation: Save changed version, operator, before/after changes, and reason to an audit trail.
// Example data returned by the app-side email acquisition API (fictitious identifier)
{
  "id": "mail_demo_001",
  "parseStatus": "parsed",
  "parserVersion": 1,
  "direction": "unknown",
  "subject": "Confirmation of Inspection Schedule",
  "receivedAt": "2026-09-10T01:02:03Z",
  "messageDate": "2026-09-10T00:58:00Z",
  "caseId": null,
  "replyToRecordId": null,
  "attachmentCount": 1,
  "originalAvailable": true
}

Deduplication and reply association are separate determinations

Cloudflare Queues provides at-least-once delivery, so implement with the assumption that the same job may arrive multiple times. Establish a unique constraint on the reception ID and parser version, and atomically perform result saving and completion status updates. Side effects like notifications also require independent deduplication keys.

Distinguish between Webhook re-delivery and a user forwarding the same email again. Message-ID can be missing, forged, or reused, so it alone is not used as a global unique key. Match using ingestion boundary, delivery path, and original hash; if a received email cannot be definitively identified as the same, it is retained as a delivery record. Also test cases where multipart boundaries or forwarding headers change.

Automatic addition to existing cases is limited to situations where reply headers point to known records, and participants and ingestion paths are also confirmed. If it points to multiple cases, or if reply relationships are lost due to manual forwarding, it remains unorganized. Do not integrate based solely on subject line matching or the same sender.

Manual affiliation changes require verification of permissions and simultaneous saving of changes and audit history. If the updated version does not match, it is returned as a conflict. Part of data design also includes not moving amounts or tasks with email movement, or considering a task complete just by ingesting a sent copy.

Even after processing for display, allow returning to the original text

HTML emails are untrusted input. Display sanitized content on screen, removing scripts and dangerous URLs. Do not load external images by default to avoid information transmission upon opening. Collapsing quoted text should remain a display-derived process, ensuring the original text can be checked even if extraction is incorrect.

Do not trust attachment extensions or Content-Types and open directly; inspect type, actual size, expansion amount of compressed files, and malware. Quarantine uninspected files and verify viewing permissions each time they are accessed. Downloading the original text is also subject to authentication.

Separately check HTTP size and memory receivable by Workers, R2 writing methods, and MIME parser memory consumption. Holding the entire raw body and parsing results simultaneously can exhaust memory with large attachments. Define limits in advance and measure signature verification to saving around those limits.

Operational logs should record reception ID, status, processing time, and failure codes, but not body, email addresses, attachments, or authentication information. Also check that original text is not mixed into parsing errors. Do not automatically forward ingested emails to access analytics or article generation AI; determine retention periods and handling of derived data upon deletion.

Before deployment, validate by changing stop positions rather than just successful cases

Testing only that the body can be displayed does not confirm that emails are not lost. Intentionally stop processing before and after saving or queue submission, and confirm that recovery from reception records is possible and that the same records or notifications are not duplicated. The following are validation items for implementing this configuration, not actual machine validation results from this article.

  • Input formats: Japanese and multiple character encodings, text only, HTML only, attachments, inline images, broken MIME, emails near the size limit.
  • Authentication: No signature, body modification, invalid key, key rotation, legitimate re-transmission, sender spoofing.
  • Failures: Stop after R2 save but before D1 commit, after D1 commit but before queue send, before/after parsing result save, and confirm recovery.
  • Association: Normal reply, manual forward, different cases with same subject, multiple candidates, simultaneous manual changes, unauthorized cases.
  • Operations: Sent Bcc, forwarding loop, auto-reply, spam, unorganized backlog, retry limit and re-submission.
  • Get API: Inability to retrieve original text/attachments outside of permissions, pagination and indexing, display of unparsed status, and log contamination in the body.

The standard for data conversion is that it can be explained again later.

A configuration that completes all processing upon receipt is easy to start small, but slow attachment inspection or external processing can lead to re-delivery. A configuration that separates saving and parsing can shorten acceptance time, but requires self-management of processing wait displays, recovery jobs, and monitoring. Choose according to the required scale and recovery requirements.

What we want to retain when digitizing emails is not just the string of the body text. The ability to trace which original it was created from, when it was received, and why it was associated with a case forms the basis for correcting misinterpretations or operational errors. At the entrance, secure the original; at the exit, return the necessary data after confirming permissions. Separating these two makes it easier for email integration to adapt to business changes.

Technical documents

We will continue to increase technical documentation.

We will continue to organize our thoughts on AI, cloud, business app development, requirements definition, and operational design into documents.

Go to technical documentation list