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

2025-03-20 08:48:00
admin
原创
38
摘要:问题描述:我正在尝试编写一个简短的程序,它将读取我 exchange/Outlook 配置文件文件夹中的电子邮件内容,以便我可以操作数据。但是,我在查找有关 python 和 exchange/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 打开和关闭的情况,但都没有任何变化。


解决方案 1:

我遇到了和你一样的问题 - 没有找到太多可行的方法。但是,以下代码非常有效。

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

解决方案 2:

我已经创建了自己的迭代器,通过 Python 迭代 Outlook 对象。问题是 Python 尝试从 Index[0] 开始迭代,但 Outlook 期望第一个项目是 Index[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

解决方案 3:

抱歉我的英语不好。使用 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()

在这里,我们可以将最早的邮件放入邮箱或任何子文件夹中。实际上,我们需要检查邮箱编号和方向。借助此分析,我们可以检查每个邮箱及其子邮箱文件夹。

同样,请找到下面的代码,我们可以看到最后/早期的邮件。我们需要如何检查。

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

这样我们就可以将最新的电子邮件放入邮箱中。根据上述代码,我们可以检查所有邮箱及其子文件夹。

解决方案 4:

我遇到了同样的问题。结合互联网(及以上)的各种方法,得出以下方法(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)

为了保持一致性,我还包含了 FileWriter 类的代码(位于 FileWrapper.py 中)。我需要这个,因为尝试将 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("
")

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

解决方案 5:

我使用以下代码加载包含每日电子邮件的 rag chromadb,并使用 chatgpt 回答有关电子邮件内容的问题

import win32com.client
client_chromadb = chromadb.PersistentClient("myPath")

session = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
namespace = session.GetNamespace("MAPI")
inbox = namespace.GetDefaultFolder(6)
messages = inbox.Items

collection_name = "emails"
 collection=client_chromadb.get_collection(collection_name,embedding_function=OpenAIEmbeddingFunction(api_key=key))

for message in messages:
    if message.Subject not in["XXX","YYY","ZZZ"]:
        print("Subject:", message.Subject)
        collection.upsert(ids=[message.EntryID],documents=[message.Body])

### my question to open ai
result= collection.query(
    query_texts=["GitHub to download the Roboflow iOS library"],
    n_results=4
)

instructions="extract the names from the manager input"
result= collection.query(
    query_texts=[instructions],
    n_results=4
)

llm=ChatOpenAI(model="gpt-3.5-turbo",temperature=0.7, openai_api_key=key)

input=""
for document in result["documents"]:
    for i in range(len(document)):
        input+=document[i]
    
#print(input)

prompt=ChatPromptTemplate.from_template(f" perform the following user task instruction: {instructions} from the follow input:{input}")

chain=prompt| llm
    
response=chain.invoke({"input":input})
output=response.content
print(output)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用