通过MAPI使用Python从Outlook中读取电子邮件 [英] Reading e-mails from Outlook with Python through MAPI

查看:447
本文介绍了通过MAPI使用Python从Outlook中读取电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简短的程序,该程序将读取我的Exchange/Outlook配置文件中某个文件夹中的电子邮件内容,以便我可以处理数据.但是我在查找有关python和Exchange/Outlook集成的更多信息时遇到了问题.很多东西要么很旧/没有文档/没有解释.我尝试了多个代码段,但似乎遇到了相同的错误.我已经尝试过蒂姆·戈登(Tim Golden)的代码:

I'm trying to write a short program that will read in the contents of e-mails within a folder on my exchange/Outlook profile so I can manipulate the data. However I'm having a problem finding much information about python and exchange/Outlook integration. A lot of stuff is either very old/has no docs/not explained. I've tried several snippets but seem to be getting the same errors. I've tried Tim Golden's code:

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)

不确定我的个人资料名称是什么,所以我尝试使用:

Not sure what my profile name is so I tried with:

session.Logon()

提示

,但它也不起作用(相同的错误).还尝试在打开和关闭Outlook的情况下都进行任何操作.

to be prompted but that didn't work either (same error). Also tried both with Outlook open and closed and neither changed anything.

推荐答案

我遇到了与您相同的问题-并没有发现很多可行的方法.但是,以下代码就像一个超级按钮.

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

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

这篇关于通过MAPI使用Python从Outlook中读取电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆