'Convert outlook emails to PDF

I am writing a code in Python that prints outlook emails. Python will read the email (.msg file) by using win32com.client and then print the email using the win32api. How do I convert the body of the email into a pdf document? This is what I have so far, this code allows me to print the email, but if the email has images or other complicated text it does not work. I think a pdf format will be better to print.

body_of_email = r'C:\Users\pythonprinter\Attachments\\' + 'messagebody.txt'
    body_mail = open(body_of_email, 'w')
    body_mail.write(str(message.body))
    body_mail.close()

    if 'print body of email' in str(message):
        win32api.ShellExecute(
                  0,
                  "print",
                  body_of_email,
                  #
                  # If this is None, the default printer will
                  # be used anyway.
                  #
                  '/d:"%s"' % win32print.GetDefaultPrinter(),
                  ".",
                  0
                )


Solution 1:[1]

i'm trying to do the same thing as you.

Weel, i'm using MSG2PDF (https://pypi.org/project/msgtopdf/) but you need to jump through a bunch of hoops to make it work. I hasn't been working on any other machines that i've tried to run my code on. Anyways, if you get it to work, it'll convert your .MSG to PDF perfectly.

After jumping through your hoops, you just need to run subprocess.run("msg2pdf -d" + " " + Directory) to convert every MSG in that directory to PDF.

Depending on the numer of .MSG you have to convert, you can also use an API, like ConvertAPI wich gives you a few hundred conversions/month for free.(https://www.convertapi.com/). It's not very usefull to me because i need to convert about 200 e-mails daily. Bummer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1