如何在 Python 中导入 .msg 文件以及本地目录中的附件

我正在处理 Outlook 电子邮件自动化任务,我将 Outlook 的 .msg 电子邮件文件存储在一个目录中。我的任务是从 .msg 文件中提取信息(电子邮件正文、附件文本等)并运行 NLP 对它们进行分类。到目前为止,我已经使用了来自https://pypi.org/project/extract-msg/和https://github.com/mattgwwalker/msg-extractor 的extract_msg 。我能够提取邮件正文,但我面临的下一个挑战是面对的是:


如何从pdf,文本文件等附件中提取文本?

如何阅读多部分电子邮件(带有回复痕迹的电子邮件)?

在编写自己的问题之前,我从多个线程中阅读了答案,但大多数答案都与直接从 Outlook.exe 中提取电子邮件有关,但是我不需要从 Outlook 中提取信息,而是将 Outlook 消息作为 .msg 存储在本地目录中文件。


到目前为止,我的进展是:


import extract_msg

import pandas as pd

import os


direct = os.getcwd() # directory object to be passed to the function for accessing emails


ext = '.msg' # type of files in the folder to be read


def DataImporter(directory, extension):

    my_list = []

    for i in os.listdir(direct):

        if i.endswith(ext):

            msg = extract_msg.Message(i)

            my_list.append([msg.filename,msg.sender,msg.to, msg.date, msg.subject, msg.body])

            global df

            df = pd.DataFrame(my_list, columns = ['File Name','From','To','Date','Subject','MailBody Text'])

    print(df.shape[0],' rows imported')


DataImporter(direct,ext)

要求是这样的:


邮件正文 = '这是一个示例电子邮件正文'。


附件 = 'Invoice123'


附件文本 = '您的发票已准备好处理'


像这样的东西,任何帮助将不胜感激,如果需要更多信息,请告诉我。


编辑:如果您知道任何其他可用于完成此任务的软件包,请发表评论。


GCT1015
浏览 821回答 3
3回答

森林海

有适合您要求的解决方案。在我的工作中,我测试了独立软件的 MSG PY 模块。这是适用于 Python 的 Microsoft Outlook .msg 文件模块。该模块允许您轻松创建/读取/解析/转换 Outlook .msg 文件。例如:from independentsoft.msg import Messagefrom independentsoft.msg import Attachmentmessage = Message(file_path = "e:\\message.msg")for i in range(len(message.attachments)):    attachment = message.attachments[i]    attachment.save("e:\\" + str(attachment.file_name))

九州编程

在 Outlook 对象模型中,使用Application.Session.OpenSharedItem: 传递完全限定的 MSG 文件名并获取MailItem对象。

缥缈止盈

发布对我有用的解决方案(如 Amey P Naik 所问)。如前所述,我尝试了多个模块,但只有extract_msg适用于手头的案例。我创建了两个函数,用于将 Outlook 消息文本和附件作为 Pandas DataFrame 导入,第一个函数将为电子邮件消息创建一个文件夹,第二个函数将数据从消息导入数据帧。附件需要在父目录的子目录上使用for循环单独处理。下面是我用注释创建的两个函数:# 1). Import the required modules and setup working directoryimport extract_msgimport osimport pandas as pddirect = os.getcwd() # directory object to be passed to the function for accessing emails, this is where you will store all .msg filesext = '.msg' #type of files in the folder to be read# 2). Create separate folder by email name and extract data def content_extraction(directory,extension):    for mail in os.listdir(directory):        try:            if mail.endswith(extension):                msg = extract_msg.Message(mail) #This will create a local 'msg' object for each email in direcory                msg.save() #This will create a separate folder for each email inside the parent folder and save a text file with email body content, also it will download all attachments inside this folder.                    except(UnicodeEncodeError,AttributeError,TypeError) as e:            pass # Using this as some emails are not processed due to different formats like, emails sent by mobile.content_extraction(direct,ext)#3).Import the data to Python DataFrame using the extract_msg module#note this will not import data from the sub-folders inside the parent directory #rather it will extract the information from .msg files, you can use a loop instead #to directly import data from the files saved on sub-folders.def DataImporter(directory, extension):    my_list = []    for i in os.listdir(direct):        try:            if i.endswith(ext):                msg = extract_msg.Message(i)                my_list.append([msg.filename,msg.sender,msg.to, msg.date, msg.subject, msg.body, msg.message_id]) #These are in-built features of '**extract_msg.Message**' class                global df                df = pd.DataFrame(my_list, columns = ['File Name','From','To','Date','Subject','MailBody Text','Message ID'])                print(df.shape[0],' rows imported')        except(UnicodeEncodeError,AttributeError,TypeError) as e:            passDataImporter(direct,ext)运行这两个函数后,您将在 Pandas DataFrame 中获得几乎所有信息,您可以根据需要使用这些信息。如果您还需要从附件中提取内容,则需要为父目录中的所有子目录创建一个循环,以根据其格式读取附件文件,例如在我的情况下格式为 .pdf、.jpg、.png ,.csv 等。从这些格式获取数据将需要不同的技术,例如从 pdf 获取数据,您将需要Pytesseract OCR 模块。如果您发现从附件中提取内容的更简单方法,请在此处发布您的解决方案以供将来参考,如果您有任何问题,请发表评论。另外,如果上述代码有任何改进的范围,请随时突出显示。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python