1

How to read email file (saved email to local drive, with “.msg” extension)?

I tried this 2 lines and it doesn't work out.

msg = open('Departure  HOUSTON EXPRESS  Port  NORFOLK.msg', 'r')
print msg.read()

I searched the web for an answer, which gave the below code:

import email
def read_MSG(file):
    email_File = open(file)
    messagedic = email.Message(email_File)
    content_type = messagedic["plain/text"]
    FROM = messagedic["From"]
    TO = messagedic.getaddr("To")
    sujet = messagedic["Subject"]
    email_File.close()
    return content_type, FROM, TO, sujet


myMSG= read_MSG(r"c:\\myemail.msg")
print myMSG

However it gives an error:

Traceback (most recent call last):
File "C:\Python27\G.py", line 19, in <module>
myMSG= read_MSG(r"c:\\myemail.msg")
File "C:\Python27\G.py", line 10, in read_MSG
messagedic = email.Message(email_File)
TypeError: 'LazyImporter' object is not callable

Some responses on Internet tell it’d better to convert the .msg to .eml before parsing but I am not really sure how.

What would be the best way to read a .msg file?

halfer
  • 19,824
  • 17
  • 99
  • 186
Mark K
  • 8,767
  • 14
  • 58
  • 118

2 Answers2

2

The code you have now looks to be completely unworkable for what you're trying to accomplish. You need to parse Outlook ".msg" files, which can be done in Python but not using the email module. But if you can use ".eml" files as you mentioned, it will be easier because the email module can read those.

To read .eml files, see email.message_from_file().

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

In case someone else comes across this like me, almost a decade after the original question:

After trying some different solutions offered here and elsewhere on the internet, I found that the easiest for me was to use extract-msg, which you can install with pip. The readme documentation is limited, but the doc-strings in the actual library is quite comprehensive.

In my case, I needed to read a .msg on disc and specifically save its attachments to disc. Here is some sample code to show how easy this is with extact-msg:

import extract_msg

msg = extract_msg.openMsg('c:/some_folder/some_mail.msg')
sender = msg.sender
subject = msg.subject
body = msg.body
time_received = msg.receivedTime  # datetime
attachment_filenames = []
for att in msg.attachments:
    att.save(customPath='c:/saved_attachments/')
    attachment_filenames.append(att.name)
levraininjaneer
  • 1,157
  • 2
  • 18
  • 38
  • 1
    fantastic! thank you for the amazing sharing! spirits like your make this world so warm and beautiful! just btw, there's only "AttributeError: 'Message' object has no attribute 'time_received'" :) – Mark K Oct 28 '22 at 09:25
  • 1
    @MarkK , aw thanks for the warm words :) Yep: looks like I used the wrong attribute in my sample code. Should be `receivedTime` not `time_received`, thanks for the heads-up. I fixed it in the post. – levraininjaneer Nov 03 '22 at 15:37