简体   繁体   English

使用 Python 通过 MAPI 从 Outlook 读取电子邮件

[英]Reading e-mails from Outlook with Python through MAPI

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.我正在尝试编写一个简短的程序,该程序将读取我的 Exchange/Outlook 配置文件中文件夹内的电子邮件内容,以便我可以操作数据。 However I'm having a problem finding much information about python and exchange/Outlook integration.但是,我在查找有关 Python 和 Exchange/Outlook 集成的大量信息时遇到了问题。 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:我试过 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 ()

However I get an error:但是我收到一个错误:

pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)

Not sure what my profile name is so I tried with:不确定我的个人资料名称是什么,所以我尝试了:

session.Logon()

to be prompted but that didn't work either (same error).被提示,但这也不起作用(同样的错误)。 Also tried both with Outlook open and closed and neither changed anything.还尝试了 Outlook 打开和关闭的情况,但都没有改变任何东西。

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

I have created my own iterator to iterate over Outlook objects via python.我创建了自己的迭代器来通过 python 迭代 Outlook 对象。 The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following methods:问题是 python 尝试从 Index[0] 开始迭代,但 Outlook 期望第一项 Index[1]... 为了使它更简单 Ruby,下面有一个具有以下方法的帮助类 Oli:

.items() - yields a tuple(index, Item)... .items() - 产生一个元组(index, Item)...

.prop() - helping to introspect outlook object exposing available properties (methods and attributes) .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

Sorry for my bad English.对不起,我的英语不好。 Checking Mails using Python with MAPI is easier,使用 Python 和MAPI检查邮件更容易,

outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()

Here we can get the most first mail into the Mail box, or into any sub folder.在这里,我们可以将最多的第一封邮件放入邮箱,或放入任何子文件夹。 Actually, we need to check the Mailbox number & orientation.实际上,我们需要检查邮箱编号和方向。 With the help of this analysis we can check each mailbox & its sub mailbox folders.借助此分析,我们可以检查每个邮箱及其子邮箱文件夹。

Similarly please find the below code, where we can see, the last/ earlier mails.同样,请找到以下代码,我们可以在其中看到最后/较早的邮件。 How we need to check.我们需要如何检查。

`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`

With this we can get most recent email into the mailbox.有了这个,我们可以将最新的电子邮件放入邮箱。 According to the above mentioned code, we can check our all mail boxes, & its sub folders.根据上面提到的代码,我们可以检查我们所有的邮箱及其子文件夹。

I had the same issue.我遇到过同样的问题。 Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)结合来自互联网(及以上)的各种方法提出以下方法(checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py).为了保持一致性,我还包括 FileWriter 类的代码(在 FileWrapper.py 中找到)。 I needed this because trying to pipe UTF8 to a file in windows did not work.我需要这个是因为尝试将 UTF8 管道传输到 Windows 中的文件不起作用。

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM