我能找到的大多数答案都已经过时了。
下面是一个用于从 Gmail 帐户下载附件的 python (>=3.6) 脚本。
确保检查底部的过滤器选项并启用不太安全的应用程序在你的谷歌帐户上。
import os
from imbox import Imbox # pip install imbox
import traceback
# enable less secure apps on your google account
# https://myaccount.google.com/lesssecureapps
host = "imap.gmail.com"
username = "username"
password = 'password'
download_folder = "/path/to/download/folder"
if not os.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 inbox
for (uid, message) in messages:
mail.mark_seen(uid) # optional, mark message as read
for idx, attachment in enumerate(message.attachments):
try:
att_fn = attachment.get('filename')
download_path = f"{download_folder}/{att_fn}"
print(download_path)
with open(download_path, "wb") as fp:
fp.write(attachment.get('content').read())
except:
print(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)
# 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')
"""
对于自签名证书,请使用:
...
import ssl
context = ssl._create_unverified_context()
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=context, starttls=False)
...
Note:
安全性较低的应用和您的 Google 帐户
为了帮助保护您的帐户安全,从 2022 年 5 月 30 日起,Google 不再
不再支持使用询问您的第三方应用程序或设备
仅使用您的用户名登录您的 Google 帐户,并且
密码。
重要提示:此截止日期不适用于 Google Workspace 或 Google
云身份客户。这些客户的执行日期
稍后将在 Workspace 博客上公布。
SRC
2022 年 8 月 22 日更新:您应该能够创建应用程序密码来解决“不太安全的应用程序”功能消失的问题。 (后者仍然可以在我的企业帐户中使用,但必须为我的消费者帐户创建应用程序密码。)使用 imaplib,我可以使用应用程序密码登录。