如何查看一段时间内收到的所有电子邮件? [英] How to check all emails that came in within a time period?

查看:168
本文介绍了如何查看一段时间内收到的所有电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法get_email(),该方法基本上每20秒发送一次,获取最新的电子邮件并对其执行一系列其他方法.

I have the following method get_email() that basically every 20 seconds, gets the latest email and performs a series of other methods on it.

def get_email():
    import win32com.client
    import os
    import time
    import datetime as dt

    date_time = time.strftime('%m-%d-%Y')

    outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
    inbox = outlook.GetDefaultFolder(6)

    messages = inbox.Items
    message = messages.GetFirst()  # any time calling GetFirst(), you can get GetNext()....
    email_subject = message.subject
    email_sender = message.SenderEmailAddress
    attachments = message.Attachments
    body_content = message.body

    print ('From: ' + email_sender)
    print ('Subject: ' + email_subject)

    if attachments.Count > 0:
        print (str(attachments.Count) + ' attachments found.')
        for i in range(attachments.Count):
                email_attachment = attachments.Item(i+1)
                report_name = date_time + '_' + email_attachment.FileName
                print('Pushing attachment - ' + report_name + ' - to check_correct_email() function.')

                if check_correct_email(email_attachment, email_subject, report_name) == True:
                    save_incoming_report(email_attachment, report_name, get_report_directory(email_subject))
                else:
                    print('Not the attachment we are looking for.')
                    # add error logging here
                    break

    else: #***********add error logging here**************
        print('No attachment found.')

我的主要问题是:

  • 是否有一种方法可以使我每小时使用GetNext()函数本身遍历每封电子邮件,而不是每20秒获取一次最新消息(这绝对不像搜索所有电子邮件那样有效)?
  • Is there a way I can iterate over every email using the GetNext() function per se every hour instead of getting the latest one every 20 seconds (which is definitely not as efficient as searching through all emails)?

鉴于有两个功能:GetFirst()GetNext()如何正确保存最新的检查内容,然后遍历所有尚未检查的内容?

Given that there are two functions: GetFirst() and GetNext() how would I properly have it save the latest checked, and then go through all the ones that have yet to be checked?

您认为在Outlook中设置其他文件夹(我可以将所有这些报告推送到该文件夹​​,然后按时间遍历它们)会更容易吗?唯一的问题是,如果自动生成了传入报告,并且电子邮件之间的时间间隔小于20秒,甚至不到1秒.

Do you think it would be easier to potentially set up a different folder in Outlook where I can push all of these reports to, and then iterate through them on a time basis? The only problem here is, if an incoming report is auto-generated and the time interval between the email is less than 20 seconds, or even 1 second.

任何帮助,我们将不胜感激!

Any help at all is appreciated!

推荐答案

您可以使用

You can use the Restrict function to restrict your messages variable to emails sent within the past hour, and iterate over each of those. Restrict takes the full list of items from your inbox and gives you a list of the ones that meet specific criteria, such as having been received in a specified time range. (The MSDN documentation linked above lists some other potential properties you could Restrict by.)

如果您每小时运行一次,则可以将收件箱限制为在过去一个小时内收到的邮件(大概是仍然需要搜索的邮件),然后遍历这些邮件.

If you run this every hour, you can Restrict your inbox to the messages you received in the past hour (which, presumably, are the ones that still need to be searched) and iterate over those.

这是一个限制过去一小时(或一分钟)内收到的电子邮件的示例:

Here's an example of restricting to emails received in the past hour (or minute):

import win32com.client
import os
import time
import datetime as dt

# this is set to the current time
date_time = dt.datetime.now()
# this is set to one hour ago
lastHourDateTime = dt.datetime.now() - dt.timedelta(hours = 1)
#This is set to one minute ago; you can change timedelta's argument to whatever you want it to be
lastMinuteDateTime = dt.datetime.now() - dt.timedelta(minutes = 1)

outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)

# retrieve all emails in the inbox, then sort them from most recently received to oldest (False will give you the reverse). Not strictly necessary, but good to know if order matters for your search
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)

# restrict to messages from the past hour based on ReceivedTime using the dates defined above.
# lastHourMessages will contain only emails with a ReceivedTime later than an hour ago
# The way the datetime is formatted DOES matter; You can't add seconds here.
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" +lastHourDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")

lastMinuteMessages = messages.Restrict("[ReceivedTime] >= '" +lastMinuteDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")

print "Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p')
print "Messages from the past hour:"

for message in lastHourMessages:
    print message.subject
    print message.ReceivedTime

print "Messages from the past minute:"

for message in lastMinuteMessages:
    print message.subject
    print message.ReceivedTime

# GetFirst/GetNext will also work, since the restricted message list is just a shortened version of your full inbox.
print "Using GetFirst/GetNext"
message = lastHourMessages.GetFirst()
while message:
    print message.subject
    print message.ReceivedTime
    message = lastHourMessages.GetNext()

您似乎每20秒运行一次,因此大概可以以不同的间隔运行它.如果您不能以固定的时间间隔可靠地运行它(然后在时间间隔中指定它,例如hours = 1),则可以保存最近检查的电子邮件的ReceivedTime,并将其用于限制搜索. (在这种情况下,保存的ReceivedTime将替换lastHourDateTime,而Restrict将检索在最后一次检查之后发送的所有电子邮件.)

You seem to have it running every 20 seconds, so presumably you could run it at a different interval. If you can't run it reliably at a regular interval (which would then be specified in the timedelta, e.g. hours=1), you could save the ReceivedTime of the most recent email checked, and use it to Restrict your search. (In that case, the saved ReceivedTime would replace lastHourDateTime, and the Restrict would retrieve every email sent after the last one checked.)

我希望这会有所帮助!

这篇关于如何查看一段时间内收到的所有电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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