[Python] Function to convert .msg file to .pdf

Discussão em 'Python' iniciado por Stack, Maio 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to automatically save an email as a pdf. Like when you open an email in MS outlook and print it as a pdf. I have tried several python packages such as extract_msg, msgtopdf, weasyprint etc but they all don't work either because wkhtmltopdf is not supported or because it doesn't provide a standard print like outlook does with default settings.

    (env) PS D:\git...\src> python -m extract_msg --pdf email.msg
    Error with file "email.msg": Traceback (most recent call last): File "C:\Users...\env\Lib\site-packages\extract_msg_main_.py", line 103, in main msg.save(**kwargs) File "C:\Users...\env\Lib\site-packages\extract_msg\msg_classes\message_base.py", line 917, in save f.write(self.getSavePdfBody(**kwargs)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users...\env\Lib\site-packages\extract_msg\msg_classes\message_base.py", line 429, in getSavePdfBody wkPath = findWk(wkPath) ^^^^^^^^^^^^^^ File "C:\Users...\Lib\site-packages\extract_msg\utils.py", line 341, in findWk raise ExecutableNotFound('Could not find wkhtmltopdf.') extract_msg.exceptions.ExecutableNotFound: Could not find wkhtmltopdf.

    (env) PS D:\git...\src>

    (env) PS D:\git...> pip install wkhtmltopdf
    Requirement already satisfied: wkhtmltopdf in c:\users...\env\lib\site-packages (0.2)

    Currently I am exploring an solution through win32com.client and the funtion PrintOut() from vba outlook: https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.printout

    The only problem I have left is that it doesn't save the pdf to a specified path and it doesn't work on the background.

    Can someone please help me? Any suggestions? This is my code:


    from pathlib import Path

    import pythoncom # type: ignore[import-untyped]
    import win32com.client # type: ignore[import-untyped]

    dir_path_email = Path(r"D:\git\...\src\email.msg")
    dir_path_email_pdf = dir_path_email.joinpath(
    Path(dir_path_email.stem).with_suffix(".pdf")
    )

    ol = win32com.client.Dispatch("outlook.Application").GetNamespace("MAPI")
    msg = ol.OpenSharedItem(dir_path_email)

    msg.PrintOut()


    Also I am getting win32com errors when rerunning. ol.Application.quit() pythoncom.CoInitialize() # preventing comerror Don't seem to help with this.

    Any help is welcome!

    Continue reading...

Compartilhe esta Página