如何在收到 24 小时内下载 Outlook 附件?

How to download an Outlook attachment within 24 hours of being received?

我正在尝试从收件箱下载所有附件。

下载 10 到 20 个文件后,程序会抛出错误。

, line 62, in
get_attachments(raw,email_id)
,line 31, in get_attachments
fileName = '{} '.format(email_id)+part.get_filename()
TypeError: must be str, not NoneType

另外,我正在尝试更改代码以在 24 小时内从 INBOX 下载收到的文件并保存在我的下载文件夹中。

import imaplib, email, os
user = "***"
password = "***"
imap_url = "smtp.outlook.com"
attachment_dir = "/GGG/"
# sets up the auth
def auth(user,password,imap_url):
    con = imaplib.IMAP4_SSL(imap_url)
    con.login(user,password)
    return con
# extracts the body from the email
def get_body(msg):
    if msg.is_multipart():
        return get_body(msg.get_payload(0))
    else:
        return msg.get_payload(None,True)
# allows you to download attachments
def get_attachments(msg,email_id):
    for part in msg.walk():
        if part.get_content_maintype()=='multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = '{} '.format(email_id)+part.get_filename()

        if bool(fileName):
            filePath = os.path.join(attachment_dir, fileName)
            with open(filePath,'wb') as f:
                f.write(part.get_payload(decode=True))
#search for a particular email
def search(key,value,con):
    result, data  = con.search(None,key,'"{}"'.format(value))
    return data
#extracts emails from byte array
def get_emails(result_bytes):
    msgs = []
    for num in result_bytes[0].split():
        typ, data = con.fetch(num, '(RFC822)')
        msgs.append(data)
    return msgs

con = auth(user,password,imap_url)

#All I added is below here
#########################################################
#A method of obtaining inbox size
inbox_size = int(con.select('INBOX')[1][0])

#Here I used a for loop to go through all email ids
for email_id in range(1,inbox_size+1):
    result, data = con.fetch(str(email_id).encode(),'(RFC822)')
    raw = email.message_from_bytes(data[0][1])
    get_attachments(raw,email_id)

根据您的描述,您可以试试下面的代码:

import win32com.client, datetime

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders('Paper & CD')
messages = inbox.Items
date_now = datetime.datetime.now().date()
date_before = (datetime.datetime.now() + datetime.timedelta(-1)).date()
messages.Find("[Start] >= """ & date_before & """ and [Start] <= """ & date_now & """")

for msg in messages:        
    for att in msg.Attachments:
        if att.FileName == 'list.csv': 
            att.SaveAsFile('C:\My\temp\' + msg.subject + att.FileName)
        att.SaveAsFile('C:\My\temp\' + att.FileName)