'Print email's body on Outlook with Python

I've been trying to print the email's body from the emails that I receive in Outlook for a while, but I'm having the following error:

Traceback (most recent call last):
  File "c:\Users\RMBORGE\Desktop\PythonLib\tempCodeRunnerFile.python", line 10, in <module>
    print(message.body)
  File "C:\Users\RMBORGE\AppData\Roaming\Python\Python39\site-packages\win32com\client\dynamic.py", line 543, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147467259, 'Unspecified error', None, None)

Could someone help me?

Please see my code below:

from email import message
import email
import win32com.client as client

outlook = client.Dispatch('Outlook.Application').GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()

print(message.body)


Solution 1:[1]

Please remember that Outlook folders may contain different kind of items - mails, documents, notes and etc. Before accessing any properties specific to a particular item type I'd recommend checking the MessageClass property first to make sure that you deal with a mail item and the required property exists for the item chosen.

See How to determine type of an outlook item in python for more information.

Another possible reason is security triggers in the Outlook object model. Read more about that in the Outlook Object Model Security Warnings article. Possible routes to avoid such triggers are:

  1. Use a low-level API on which Outlook is based on - Extended MAPI. Or just consider using any wrapper around that API such as Redemption.
  2. Use components for turning on/off security issues in Outlook, see Outlook Security Manager.
  3. Use group policy to configure security issues when dealing with OOM.
  4. Install any antivirus software with latest databases.

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