4 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
我能找到的大多數(shù)答案都已過(guò)時(shí)。
這是一個(gè)用于從 Gmail 帳戶下載附件的 python (>=3.6) 腳本。
確保檢查底部的過(guò)濾器選項(xiàng)并在您的谷歌帳戶上啟用不太安全的應(yīng)用程序。
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='sender@example.org')
# Messages sent TO
messages = mail.messages(sent_to='receiver@example.org')
# 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')
"""
對(duì)于自簽名證書(shū),請(qǐng)使用:
...
import ssl
context = ssl._create_unverified_context()
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=context, starttls=False)
...
筆記:
不太安全的應(yīng)用和您的 Google 帳戶
為幫助確保您的帳戶安全,自 2022 年 5 月 30 日起,Google 不再支持使用第三方應(yīng)用或設(shè)備,這些應(yīng)用或設(shè)備要求您僅使用您的用戶名和密碼登錄您的 Google 帳戶。
重要提示:此截止日期不適用于 Google Workspace 或 Google Cloud Identity 客戶。這些客戶的執(zhí)行日期將在稍后的 Workspace 博客上公布。
SRC
2022 年 8 月 22 日更新:您應(yīng)該能夠創(chuàng)建一個(gè)應(yīng)用程序密碼來(lái)解決“不太安全的應(yīng)用程序”功能消失的問(wèn)題。(后者仍然可以在我的企業(yè)帳戶中使用,但必須為我的消費(fèi)者帳戶創(chuàng)建一個(gè)應(yīng)用程序密碼。)使用 imaplib,我可以使用應(yīng)用程序密碼登錄。

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
我發(fā)現(xiàn)這對(duì)我來(lái)說(shuō)最有效。只需在運(yùn)行程序時(shí)保持您的前景打開(kāi),它就會(huì)提取具有特定主題行的未讀郵件。
import datetime
import os
import win32com.client
path = os.path.expanduser("~/Documents/xyz/folder_to_be_saved") #location o file today = datetime.date.today() # current date if you want current
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") #opens outlook
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
def saveattachemnts(subject):
for message in messages:
if message.Subject == subject and message.Unread:
#if message.Unread: #I usually use this because the subject line contains time and it varies over time. So I just use unread
# body_content = message.body
attachments = message.Attachments
attachment = attachments.Item(1)
for attachment in message.Attachments:
attachment.SaveAsFile(os.path.join(path, str(attachment)))
if message.Subject == subject and message.Unread:
message.Unread = False
break
saveattachemnts('EXAMPLE 1')
saveattachemnts('EXAMPLE 2')

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
from imap_tools import MailBox
# get all attachments from INBOX and save them to files
with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch():
for att in msg.attachments:
print(att.filename, att.content_type)
with open('C:/1/{}'.format(att.filename), 'wb') as f:
f.write(att.payload)
https://github.com/ikvk/imap_tools

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
我使用該解決方案從郵箱獲取附件。由您決定,下載或保存到本地變量。另外請(qǐng)注意,我首先閱讀了所有消息,因?yàn)榇蠖鄶?shù)時(shí)候盒子都是空的:
import imaplib
import email
class MailBox:
SMTP_SERVER = 'imap.gmail.com'
SMTP_PORT = 993
USER = '<user_email>'
PASSWORD = '<password>'
def __init__(self):
self.imap = imaplib.IMAP4_SSL(host=self.SMTP_SERVER, port=self.SMTP_PORT)
self.imap.login(self.USER, self.PASSWORD)
def __enter__(self):
self.emails = self._get_all_messages()
def __exit__(self, exc_type, exc_value, exc_traceback):
self.imap.close()
self.imap.logout()
def fetch_message(self, num=-1):
_, data = self.imap.fetch(self.emails[num], '(RFC822)')
_, bytes_data = data[0]
email_message = email.message_from_bytes(bytes_data)
return email_message
def get_attachment(self, num=-1):
for part in self.fetch_message(num).walk():
if part.get_content_maintype() == 'multipart' or part.get('Content-Disposition') is None:
continue
if part.get_filename():
return part.get_payload(decode=True).decode('utf-8').strip()
def _get_all_messages(self):
self.imap.select('Inbox')
status, data = self.imap.search(None, 'ALL')
return data[0].split()
添加回答
舉報(bào)