Python Forum
Reading email messages on Outlook
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading email messages on Outlook
#1
I am writing a python code to read emails on Microsoft Outlook, looking for files attached (any file *.msg), read these .msg files and grab any URL contained in the body of the message.

So, the final idea is:
Read Emails -> Is there attachments? -> If yes -> Is the file extension equals to .msg? -> If yes, read this file and grab URL link.

First, I wrote a simple python script just to read the emails and log the name of the attached files. However, when there is a different file attached (like .mp3 for instance), my script returns the error:

Error:
Traceback (most recent call last): File "phishing-mailbox.py", line 63, in <module> if str(attch.FileName).endswith('.mp3') is True: File "C:\Program Files\Python36\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Outlook cannot perform this action on this type of attachment.', None, 0, -2147467259), None)
I am using the library win32com in my script. So, I would like to know if anyone knows how to handle this Outlook return error?

I tried to ignore it using the code below, but I got the same error:

if str(attch.FileName).endswith('.mp3') is True:
print("File attached is .mp3!")
continue
Reply
#2
I suggest you to use exceptions handlers for each extensions of file.
Something like:

list_of_extensions = ['.doc', '.mp3', '.msg', ...]
for ext in list_of_extensions:
    try:
        if str(attch.FileName).endswith(ext):
            print(f'File is {ext}!')
    except Exception as e:
        print(f'Error with {ext}\n{e}')
Reply
#3
gontajones,
Thank you very much for the tip. It worked.
I really appreciate that.
Reply
#4
Is there a reason you're interfacing with Outlook, instead of just querying the imap server directly?
Reply
#5
Hello nilamo,

Yes, for now I have a particular reason that I need to interface with Outlook... :(

Btw, do you have an idea how can I read the content of an attached message (.msg and .eml files) without exporting and saving the file in my computer?

I mean, I'm parsing the emails on Inbox, checking which one have attached messages (.msg and/or .eml) and I need to read these attached messages. Any idea how to read the attached file?

Thanks in advanced.
Reply
#6
Hi johnjohn

Can i know the code how you do or read outlook mail thru python,
I need to do same thing i need fetch mail contant in mail centent need to , subjectline, mailbody, to, cc,...like this.

Please help me out this.
Reply
#7
Hi pramodb35,

Follow a sample of code to fetch mail contents on Outlook:

# import the win32com library
import win32com.client

# get Outlook application object
Outlook = win32com.client.Dispatch("Outlook.Application")

# get the Namespace / Session object
namespace = Outlook.Session

# get Inbox Folders' name
inboxfolder = namespace.Folders.Folders('Inbox')

# get messages on Inbox folder
messages = inboxfolder.Items

# get message contents
for message in messages:
    sender = message.Sender
    receiver = message.To
    cc = message.Cc
    subject = message.Subject
    body = message.Body
I hope this peace of code can help you.
Reply
#8
Anyone have an idea how to read the content of an attached message (.msg file)?
Reply
#9
Hi John,

I am getting below error.
Error:
C:\Users\pramod.singh\AppData\Local\Programs\Python\Python36-32\python.exe "C:/C drive/Python/test.py" Traceback (most recent call last): File "C:/C drive/Python/test.py", line 33, in <module> inboxfolder = namespace.Folders.Folders('Inbox') File "C:\Users\pramod.singh\AppData\Roaming\Python\Python36\site-packages\win32\com\client\dynamic.py", line 588, in __getattr__ raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: <unknown>.Folders Process finished with exit code 1
Reply
#10
I am getting the following error with your code.

Traceback (most recent call last):
File "C:/Users/kenel/.PyCharmEdu2018.3/config/scratches/TEST2.py", line 12, in <module>
inboxfolder = namespace.Folders.Folders('Inbox')
File "C:\Users\kenel\PycharmProjects\Photo\venv\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.Folders

Can you help please.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Outlook Inbox for set of values cubangt 1 1,043 Jun-28-2023, 09:29 PM
Last Post: cubangt
  Save image from outlook email cubangt 1 688 Jun-07-2023, 06:52 PM
Last Post: cubangt
  Mark outlook emails as read using Python! shane88 2 6,535 Feb-24-2022, 11:19 PM
Last Post: Pedroski55
  Trying out the parsing/reading of emails from my outlook cubangt 0 6,141 Jan-12-2022, 08:59 PM
Last Post: cubangt
  Help Needed | Read Outlook email Recursively & download attachment Vinci141 1 4,070 Jan-07-2022, 07:38 PM
Last Post: cubangt
  Need Outlook send email code using python srikanthpython 3 8,205 Feb-28-2021, 01:53 PM
Last Post: asyswow64
  reading shared outlook emails zarize 0 2,443 Mar-03-2020, 01:47 PM
Last Post: zarize
  logging messages ahead of print messages vindo 6 3,185 Jun-18-2019, 02:45 PM
Last Post: vindo
  How to Find a specific email in Outlook with Python Code jassi123 2 3,822 Oct-31-2018, 08:07 AM
Last Post: jassi123
  [Outlook] How to delete items from To-Do List? Winfried 1 3,391 Oct-19-2018, 09:05 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020