2

I am trying to print emails from Outlook using win32com. The only issue is when I am trying to access MailItem.SentOn or MailItem.ReceivedTime, Python crashes with windows showing "Python has stopped working" dialog window. What can be the cause of this issue?

Here is my code:

import win32com
import win32com.client
import os
import sys
import re
from datetime import datetime

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts = win32com.client.Dispatch("Outlook.Application").Session.Accounts

inbox = outlook.Folders(accounts[0].DeliveryStore.DisplayName)
folders = inbox.Folders

inbox_messages = folders("Inbox").Items
msg = inbox_messages.GetFirst()

while msg:
    print(msg.SenderEmailAddress)
    print(msg.Subject)
    print (msg.SentOn)
    msg = inbox_messages.GetNext()

I am using Office 365 and Python 3.7.0 on Windows 10.

Error Window

2 Answers2

1

I have this same issue. My script works fine in Python 3.6.5, but fails in 3.7.0

0

so not all mails will have SenderEmailAddress and SentOn. I tried your program on my inbox and it seems to crash on a mail that was generated by outlook - a undeliverable mail generated by outlook:

Your message to xxxx@xxxx.com couldn't be delivered.
A custom mail flow rule created by an admin at xxx.onmicrosoft.com has blocked your message.

.

Traceback (most recent call last):
  File "xxxx\outl.py", line 24, in <module>
    print (msg.SentOn)
  File "xxx\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: GetNext.SentOn

not sure why it crashes python for you but a crash with stack for me but i think you should handle the case where the attributes can be missing.

hmad
  • 159
  • 8
  • Hi hmad. Thank you for your response, I think in your case it actually went over some other emails before giving you this message. Actually in my original code, there is a line to check the subject which makes sure that the email will have a sender and SentOn property attached to it. In my case, the first email that is read by the code, will crash python on accessing SentOn property. Just commenting that line fixes everything. – user10236586 Aug 20 '18 at 15:00