python读取msg文件_读取.msg文件的属性

I am trying to read a .msg file to get the sender, recipients, and title.

I'm making this script for my workplace where I'm only allowed to install default python libraries so I want to use the email module to do this.

On the python website I found some examples of using the email module. https://docs.python.org/3/library/email.examples.html

Near the end of the page it talks about getting the sender, subject and recipient. I've tried using this code like this:

# Import the email modules we'll need

from email import policy

from email.parser import BytesParser

with open('test_email.msg', 'rb') as fp:

msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will

# be converted to unicode:

print('To:', msg['to'])

print('From:', msg['from'])

print('Subject:', msg['subject'])

This results in an output:

To: None

From: None

Subject: None

I checked the file test_email.msg, it is a valid email.

When I add a line of code

print(msg)

I get an output of a garbled email the same as if I opened the .msg file in notepad.

Can anybody suggest why the email module isn't finding the sender/recipient/subject correctly?

解决方案

You are apparently attempting to read some sort of proprietary binary format. The Python email library does not support this; it only handles traditional (basically text) RFC822 / RFC5322 format.

To read Microsoft's OLE formats, you will need a third-party module, and some patience, voodoo, and luck.

Also, for the record, there is no unambigious definition of .msg. Outlook uses this file extension for its files, but it is used on other files in other formats as well, including also traditional RFC822 files.

(The second link attempts to link to the MS-OXMSG spec on MSDN; but Microsoft have in the past regarded URLs as some sort of depletable resource which runs out when you use it, so the link will probably stop working if enough people click on it.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值