在python中将msg转换为pdf

问题描述 投票:0回答:3

我真的需要你的帮助来解决问题!显然,我的知识不足以找到解决方案。 所以,我已经创建并保存了一些消息文件。现在我需要编写一个函数来帮助我从 msg 文件(会有很多)创建 pdf。 我将非常感谢您的帮助!

python-3.x pdf data-conversion msg
3个回答
2
投票

发布对我有用的解决方案(按照 Amey P Naik 的要求)。如前所述,我尝试了多个模块,但只有 extract_msg 适用于当前的情况。我创建了两个函数,用于将 Outlook 消息文本和附件导入为 Pandas DataFrame,第一个函数将为电子邮件创建一个文件夹,第二个函数将数据从消息导入到数据帧。需要在父目录中的子目录上使用 for 循环单独处理附件。以下是我用注释创建的两个函数:

 # 1). Import the required modules and setup working directory
    
    import extract_msg
    import os
    import pandas as pd
    direct = os.getcwd() # directory object to be passed to the function for accessing emails, this is where you will store all .msg files
    ext = '.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:
            pass

DataImporter(direct,ext)

运行这两个函数后,您将在 Pandas DataFrame 中获得几乎所有信息,您可以根据需要使用它们。如果您还需要从附件中提取内容,则需要为父目录内的所有子目录创建一个循环,以按照附件文件的格式读取附件文件,就像在我的例子中,格式为.pdf、.jpg、.png 、.csv 等。从这些格式获取数据将需要不同的技术,例如从 pdf 获取数据,您将需要 Pytesseract OCR 模块。

如果您找到更简单的方法从附件中提取内容,请将您的解决方案发布在这里以供将来参考,如果您有任何问题,请评论。另外,如果上述代码有任何改进范围,请随时突出显示。


0
投票

仅供记录,因为我刚刚尝试了这种方法:extract_msg 同时支持使用如下命令本地生成 pdf 文件:

python -m extract_msg --pdf  email.msg


0
投票

在尝试了多种方法(例如 aspose、msg2pdf、pywin32 和更多模块/包)之后。我得出的结论是以下方法对我有用。

WeasyPrint 是一个智能解决方案,可帮助 Web 开发人员创建 PDF 文档。

提取保存在 Microsoft Outlook .msg 文件中的电子邮件和附件

安装所需模块

!pip install weasyprint #
!pip install extract-msg==0.41.1 #

导入所需模块

import extract_msg
from weasyprint import HTML

将 msg 转换为 pdf

# Reading msg file
msg = extract_msg.openMsg("c:/abcd/testing.msg")

# saving as html format
with open("c:/abcd/test_case.html","wb") as file:
    file.write(msg.getSaveHtmlBody())

#  to create PDF documents from HTML
HTML("c:/abcd/test_case.html").write_pdf("c:/abcd/test_case_output.pdf")
© www.soinside.com 2019 - 2024. All rights reserved.