通过 MAPI 使用 Python 从 Outlook 读取电子邮件
- 2025-03-20 08:48:00
- admin 原创
- 39
问题描述:
我正在尝试编写一个简短的程序,它将读取我 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)
扫码咨询,免费领取项目管理大礼包!