Email Ingestion for Enterprise RAG
Ingest mailboxes and .eml/.msg files: threads, attachments, quoted text, metadata and privacy.
A lot of enterprise knowledge lives in email: decisions, customer commitments, troubleshooting threads and attachments that never reached a wiki. Email is also among the most sensitive and messiest content to index. Messages repeat each other through quoting, threads branch, signatures and disclaimers add noise, and attachments carry most of the substance. This lesson builds an email ingestion pipeline: parse .eml and Outlook .msg files, pull mail from Microsoft 365, strip quoted text, group threads, handle attachments, and keep privacy under control.
What you will learn
- How to parse
.emlfiles with Python's standard library, including bodies and attachments - How to read Outlook
.msgfiles and Microsoft 365 mailboxes - How to remove quoted replies, signatures and disclaimers
- How to group messages into threads and turn them into RAG documents with safe metadata
Prerequisites
Email contains personal data and confidential conversations. Index mailboxes only with a clear legal basis and approval (for example, a shared support mailbox, not personal inboxes), apply the mailbox's access rules to every chunk, redact what you do not need, and agree retention rules with your privacy and legal teams.
Installation
pip install beautifulsoup4 extract-msg msal requests
The email module used for .eml files is part of Python's standard library.
Step 1: Parse .eml files
With policy=default, Python's email parser returns a modern EmailMessage with helpers to pick the best body and iterate attachments:
from dataclasses import dataclass, field
from email import policy
from email.parser import BytesParser
from email.utils import getaddresses, parsedate_to_datetime
from pathlib import Path
from bs4 import BeautifulSoup
@dataclass
class Email:
message_id: str
subject: str
sender: str
recipients: list[str]
date: str
body: str
in_reply_to: str = ""
references: list[str] = field(default_factory=list)
attachments: list[tuple[str, bytes]] = field(default_factory=list)
def html_to_text(html: str) -> str:
return BeautifulSoup(html, "html.parser").get_text("\n")
def parse_eml(path: str) -> Email:
with open(path, "rb") as f:
msg = BytesParser(policy=policy.default).parse(f)
body_part = msg.get_body(preferencelist=("plain", "html"))
body = ""
if body_part is not None:
content = body_part.get_content()
body = content if body_part.get_content_type() == "text/plain" else html_to_text(content)
attachments = [(part.get_filename() or "attachment", part.get_payload(decode=True) or b"")
for part in msg.iter_attachments()]
recipients = [addr for _, addr in getaddresses(msg.get_all("To", []) + msg.get_all("Cc", []))]
date = msg["Date"]
return Email(
message_id=str(msg["Message-ID"] or path).strip(),
subject=str(msg["Subject"] or ""),
sender=getaddresses([str(msg["From"] or "")])[0][1],
recipients=recipients,
date=parsedate_to_datetime(date).isoformat() if date else "",
body=body,
in_reply_to=str(msg["In-Reply-To"] or "").strip(),
references=str(msg["References"] or "").split(),
attachments=attachments,
)
emails = [parse_eml(str(p)) for p in Path("mail_export").glob("*.eml")]
print(len(emails), emails[0].subject if emails else None)
Step 2: Outlook .msg files
Outlook's .msg format is not a MIME file. The extract-msg library reads it; the attribute names below follow its documentation, so check them against your installed version:
import extract_msg
def parse_msg(path: str) -> Email:
with extract_msg.Message(path) as m:
return Email(
message_id=str(m.messageId or path),
subject=m.subject or "",
sender=m.sender or "",
recipients=[r.strip() for r in (m.to or "").split(";") if r.strip()],
date=str(m.date or ""),
body=m.body or "",
attachments=[(a.longFilename or a.shortFilename or "attachment", a.data or b"")
for a in m.attachments if isinstance(a.data, bytes)],
)
Step 3: Microsoft 365 mailboxes through Microsoft Graph
For a shared mailbox in Microsoft 365, use the Graph API with an app registration that has the Mail.Read application permission, ideally restricted to specific mailboxes with an application access policy. The token code is the same as in Ingesting Documents from Cloud Storage.
import base64
import requests
GRAPH = "https://graph.microsoft.com/v1.0"
def graph_messages(token: str, mailbox: str, since_iso: str):
"""Yield messages received since a time, following Graph pagination."""
url = (f"{GRAPH}/users/{mailbox}/messages"
f"?$filter=receivedDateTime ge {since_iso}"
"&$select=id,internetMessageId,subject,from,toRecipients,receivedDateTime,body,conversationId,hasAttachments"
"&$top=50")
headers = {"Authorization": f"Bearer {token}", "Prefer": 'outlook.body-content-type="text"'}
while url:
body = requests.get(url, headers=headers, timeout=30).json()
yield from body.get("value", [])
url = body.get("@odata.nextLink")
def graph_attachments(token: str, mailbox: str, message_id: str) -> list[tuple[str, bytes]]:
url = f"{GRAPH}/users/{mailbox}/messages/{message_id}/attachments"
items = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=60).json().get("value", [])
return [(a["name"], base64.b64decode(a["contentBytes"]))
for a in items if a.get("@odata.type") == "#microsoft.graph.fileAttachment"]
The Prefer: outlook.body-content-type="text" header asks Graph for plain-text bodies. Each message's conversationId groups it with its thread. For efficient ongoing sync, Graph also offers a delta query on mail folders.
Step 4: Remove quoted text, signatures and disclaimers
Replies quote earlier messages, so indexing every body in full repeats the same text many times. Keep only the new part of each message:
import re
REPLY_MARKERS = [
re.compile(r"^On .{5,200} wrote:\s*$", re.M), # Gmail / Apple Mail
re.compile(r"^-{2,}\s*Original Message\s*-{2,}", re.M | re.I), # Outlook
re.compile(r"^From: .+\r?\nSent: .+", re.M), # Outlook header block
]
SIGNATURE = re.compile(r"^(--\s*$|Best regards|Kind regards|Thanks,?\s*$)", re.M | re.I)
DISCLAIMER = re.compile(r"(This e-?mail and any attachments are confidential.*)", re.I | re.S)
def new_content(body: str) -> str:
cut = len(body)
for marker in REPLY_MARKERS:
m = marker.search(body)
if m:
cut = min(cut, m.start())
text = body[:cut]
text = "\n".join(line for line in text.splitlines() if not line.lstrip().startswith(">"))
m = SIGNATURE.search(text)
if m and m.start() > len(text) * 0.5: # only trim a signature near the end
text = text[:m.start()]
return DISCLAIMER.sub("", text).strip()
These heuristics cover common clients; collect examples from your own mail and add patterns. Test that you do not cut real content: log the share of each body that was removed.
Step 5: Group threads and build documents
A thread is usually a better retrieval unit than a single message: it carries the question and the answer together. Group by conversationId (Graph) or by the root of the References chain (.eml), and build one document per thread:
from collections import defaultdict
def thread_key(e: Email) -> str:
return e.references[0] if e.references else (e.in_reply_to or e.message_id)
def thread_documents(emails: list[Email], mailbox: str, allowed_groups: list[str]) -> list[dict]:
threads = defaultdict(list)
for e in emails:
threads[thread_key(e)].append(e)
docs = []
for key, messages in threads.items():
messages.sort(key=lambda e: e.date)
parts = [f"[{e.date[:10]}] {e.sender}:\n{new_content(e.body)}" for e in messages]
docs.append({
"id": f"email-thread:{key}",
"text": f"Subject: {messages[0].subject}\n\n" + "\n\n".join(parts),
"metadata": {
"source": "email", "mailbox": mailbox, "subject": messages[0].subject,
"first_date": messages[0].date, "last_date": messages[-1].date,
"message_count": len(messages),
"allowed_groups": allowed_groups, # from the mailbox's access rules
},
})
return docs
Attachments should go through your normal document loaders and become their own documents, with metadata linking them to the thread ("thread_id") and the same permissions. Chunk long threads by message boundaries rather than fixed sizes.
Step 6: Apply privacy controls
- Redact phone numbers, addresses and identifiers you do not need before embedding (PII Redaction).
- Minimise metadata: store sender roles or domains rather than every recipient's address if full addresses are not needed.
- Exclude messages marked personal, private or confidential, and mail from specific senders or folders.
- Honour deletion: when a message is deleted or a retention period ends, remove its chunks (Data Retention and Deletion).
Common errors and troubleshooting
- Garbled characters: let the email parser decode bodies (
get_content()); do not decode bytes yourself. - Empty bodies: the message is HTML-only or the content is in an attachment; fall back to HTML and process attachments.
- The same text retrieved many times: quoted replies were not removed or threads were not grouped.
- Graph 403 errors: the app lacks
Mail.Read, admin consent, or access to that mailbox.
Key takeaways
- Parse
.emlwith Python'semailpackage,.msgwithextract-msg, and Microsoft 365 mail with Graph. - Keep only new content per message by removing quoted replies, signatures and disclaimers.
- Index threads as documents and attachments as linked documents, with mailbox permissions on every chunk.
- Email needs strict privacy controls: approval, redaction, minimal metadata and deletion handling.
Frequently asked questions
Should I index individual messages or threads?
Threads usually retrieve better because questions and answers stay together. For very long threads, chunk by message while keeping the subject and thread id on each chunk.
Can I index everyone's mailbox?
That is a legal and policy decision, not a technical one, and it is rarely appropriate. Shared, purpose-specific mailboxes are the usual starting point.
Practice exercises
- Export 50 messages from a test mailbox as
.eml, build thread documents and measure how much text quoting removal saves. - Add attachment processing that sends PDFs and Office files to the loaders from earlier lessons.