简体   繁体   English

Python 从 Outlook 读取最后 10 封电子邮件

[英]Python read last 10 emails from Outlook

I can read my last email from my Outlook and send all the results according to each line's content.我可以从 Outlook 中阅读上一封电子邮件,并根据每一行的内容发送所有结果。

However, I am unable to find the way to read my last 10 emails to be added to the fileCollect.txt file.但是,我无法找到读取要添加到 fileCollect.txt 文件中的最后 10 封电子邮件的方法。

Any ideas how I could do this?任何想法我怎么能做到这一点? Here is my current code:这是我当前的代码:


import win32com.client
import csv

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()



fileCollect = open("fileCollect.txt",'a')
delimiter = "¿"
fileCollect.write( str(message.Sender) + delimiter + str(message.Subject)+ delimiter + str(message.Body) )
fileCollect.close()


csvfile = open("csvfile.csv",'a')

with open("fileCollect.txt","r") as outfile:
    for line in outfile:
        if line.find("test") != -1:
            csvfile.write(line)

csvfile.close()

The Items collection will not be sorted in any particular order until you actually sort it by calling Items.Sort.在您通过调用 Items.Sort 实际对其进行排序之前,不会按任何特定顺序对 Items 集合进行排序。 The VB script below sorts the collection by ReceivedTime in the descending order:下面的 VB 脚本按 ReceivedTime 降序对集合进行排序:

set messages = inbox.Items
messages.Sort("ReceivedTime", True)
set message = messages.GetFirst()
while not (message Is Nothing)
  MsgBox message.Subject
  set message = messages.GetNext()
wend

You can get the last 10 messages by specifying a negative index:您可以通过指定负索引来获取最后 10 条消息:

last_10_messages = messages[-10:]

This will return an array from messages[-10], which is the 10th to the last message, to the last message in the messages array.这将从messages[-10](从第10 条到最后一条消息)返回一个数组到消息数组中的最后一条消息。

  1. use len(inbox.Items) to get the length of the inbox.使用 len(inbox.Items) 获取收件箱的长度。
  2. use inbox.Items.Item(i) to get i-th email in the inbox.使用 inbox.Items.Item(i) 在收件箱中获取第 i 封电子邮件。

Ref: https://docs.microsoft.com/en-us/office/vba/api/outlook.items.item参考: https ://docs.microsoft.com/en-us/office/vba/api/outlook.items.item

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

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