Skip to main content

Email

This notebook shows how to load email (.eml) or Microsoft Outlook (.msg) files.

使用Unstructured

#!pip install unstructured
from langchain.document_loaders import UnstructuredEmailLoader
loader = UnstructuredEmailLoader("example_data/fake-email.eml")
data = loader.load()
data
    [Document(page_content='This is a test email to use for unit tests.\n\nImportant points:\n\nRoses are red\n\nViolets are blue', metadata={'source': 'example_data/fake-email.eml'})]

保留元素

在底层,Unstructured为不同的文本块创建不同的“元素”。默认情况下,我们将它们合并在一起,但您可以通过指定mode="elements"来轻松保留该分离。

loader = UnstructuredEmailLoader("example_data/fake-email.eml", mode="elements")
data = loader.load()
data[0]
    Document(page_content='This is a test email to use for unit tests.', metadata={'source': 'example_data/fake-email.eml', 'filename': 'fake-email.eml', 'file_directory': 'example_data', 'date': '2022-12-16T17:04:16-05:00', 'filetype': 'message/rfc822', 'sent_from': ['Matthew Robinson <mrobinson@unstructured.io>'], 'sent_to': ['Matthew Robinson <mrobinson@unstructured.io>'], 'subject': 'Test Email', 'category': 'NarrativeText'})

处理附件

您可以通过在构造函数中设置process_attachments=True来使用UnstructuredEmailLoader处理附件。默认情况下,附件将使用unstructured中的partition函数进行分区。您可以通过将函数传递给attachment_partitioner关键字参数来使用不同的分区函数。

loader = UnstructuredEmailLoader(
"example_data/fake-email.eml",
mode="elements",
process_attachments=True,
)
data = loader.load()
data[0]
    Document(page_content='This is a test email to use for unit tests.', metadata={'source': 'example_data/fake-email.eml', 'filename': 'fake-email.eml', 'file_directory': 'example_data', 'date': '2022-12-16T17:04:16-05:00', 'filetype': 'message/rfc822', 'sent_from': ['Matthew Robinson <mrobinson@unstructured.io>'], 'sent_to': ['Matthew Robinson <mrobinson@unstructured.io>'], 'subject': 'Test Email', 'category': 'NarrativeText'})

使用OutlookMessageLoader

#!pip install extract_msg
from langchain.document_loaders import OutlookMessageLoader
loader = OutlookMessageLoader("example_data/fake-email.msg")
data = loader.load()
data[0]
    Document(page_content='This is a test email to experiment with the MS Outlook MSG Extractor\r\n\r\n\r\n-- \r\n\r\n\r\nKind regards\r\n\r\n\r\n\r\n\r\nBrian Zhou\r\n\r\n', metadata={'subject': 'Test for TIF files', 'sender': 'Brian Zhou <brizhou@gmail.com>', 'date': 'Mon, 18 Nov 2013 16:26:24 +0800'})