python自动下载邮件附件_使用python从邮件下载附件

importosfromimboximportImbox# pip install imboximporttraceback# enable less secure apps on your google account# https://myaccount.google.com/lesssecureappshost="imap.gmail.com"username="username"password='password'download_folder="/path/to/download/folder"ifnotos.path.isdir(download_folder):os.makedirs(download_folder,exist_ok=True)mail=Imbox(host,username=username,password=password,ssl=True,ssl_context=None,starttls=False)messages=mail.messages()# defaults to inboxfor(uid,message)inmessages:mail.mark_seen(uid)# optional, mark message as readforidx,attachmentinenumerate(message.attachments):try:att_fn=attachment.get('filename')download_path=f"{download_folder}/{att_fn}"print(download_path)withopen(download_path,"wb")asfp:fp.write(attachment.get('content').read())except:passprint(traceback.print_exc())mail.logout()"""

Available Message filters:

# Gets all messages from the inbox

messages = mail.messages()

# Unread messages

messages = mail.messages(unread=True)

# Flagged messages

messages = mail.messages(flagged=True)

# Un-flagged messages

messages = mail.messages(unflagged=True)

# Flagged messages

messages = mail.messages(flagged=True)

# Un-flagged messages

messages = mail.messages(unflagged=True)

# Messages sent FROM

messages = mail.messages(sent_from='[email protected]')

# Messages sent TO

messages = mail.messages(sent_to='[email protected]')

# Messages received before specific date

messages = mail.messages(date__lt=datetime.date(2018, 7, 31))

# Messages received after specific date

messages = mail.messages(date__gt=datetime.date(2018, 7, 30))

# Messages received on a specific date

messages = mail.messages(date__on=datetime.date(2018, 7, 30))

# Messages whose subjects contain a string

messages = mail.messages(subject='Christmas')

# Messages from a specific folder

messages = mail.messages(folder='Social')

"""

你可能感兴趣的:(python自动下载邮件附件)