通过MAPI使用Python读取Outlook邮件
我正在尝试写一个小程序,目的是读取我在Exchange/Outlook账户中某个文件夹里的电子邮件内容,这样我就可以对这些数据进行处理。不过,我发现关于Python和Exchange/Outlook集成的信息很少。很多资料要么很旧,要么没有文档,要么解释得不清楚。我试过几个代码片段,但总是遇到同样的错误。我试过Tim Golden的代码:
import win32com.client
session = win32com.client.gencache.EnsureDispatch ("MAPI.Session")
#
# Leave blank to be prompted for a session, or use
# your own profile name if not "Outlook". It is also
# possible to pull the default profile from the registry.
#
session.Logon ("Outlook")
messages = session.Inbox.Messages
#
# Although the inbox_messages collection can be accessed
# via getitem-style calls (inbox_messages[1] etc.) this
# is the recommended approach from Microsoft since the
# Inbox can mutate while you're iterating.
#
message = messages.GetFirst ()
while message:
print message.Subject
message = messages.GetNext ()
但是我遇到了一个错误:
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
我不太确定我的账户名称是什么,所以我试着用:
session.Logon()
想要系统提示我输入,但这也没用(还是同样的错误)。我还尝试过在Outlook打开和关闭的情况下运行,但都没有改变任何情况。
4 个回答
4
抱歉我的英语不好。
用MAPI在Python中检查邮件其实很简单。
outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()
在这里,我们可以获取邮箱里最早的一封邮件,或者任何子文件夹里的邮件。实际上,我们需要查看邮箱的编号和方向。通过这个分析,我们可以检查每个邮箱及其子文件夹。
下面的代码可以帮助我们查看最新的或之前的邮件。我们需要知道怎么去检查。
`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`
这样我们就能获取邮箱里最新的邮件。根据上面提到的代码,我们可以检查所有的邮箱及其子文件夹。
13
我创建了一个自己的迭代器,用来通过Python遍历Outlook对象。问题是,Python从索引0开始遍历,但Outlook却希望第一个项目的索引是1……为了让它更简单,就像Ruby那样,下面有一个辅助类Oli,包含以下方法:
.items() - 返回一个元组(index, Item)...
.prop() - 帮助查看Outlook对象,显示可用的属性(方法和属性)
from win32com.client import constants
from win32com.client.gencache import EnsureDispatch as Dispatch
outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
class Oli():
def __init__(self, outlook_object):
self._obj = outlook_object
def items(self):
array_size = self._obj.Count
for item_index in xrange(1,array_size+1):
yield (item_index, self._obj[item_index])
def prop(self):
return sorted( self._obj._prop_map_get_.keys() )
for inx, folder in Oli(mapi.Folders).items():
# iterate all Outlook folders (top level)
print "-"*70
print folder.Name
for inx,subfolder in Oli(folder.Folders).items():
print "(%i)" % inx, subfolder.Name,"=> ", subfolder
84
我遇到过和你一样的问题 - 找不到什么有效的解决办法。不过,下面这段代码效果很好。
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content