5,914
社区成员
我写了个下载邮箱附件的代码,
import imaplib
import email
from email.header import decode_header
import datetime
import os
# 邮箱设置
username = 'slyzxfxzb@shandong.cn'
password = '*****' #密码隐藏了
imap_url = 'mail.shandong.cn' # 请根据你的邮箱提供商修改此URL
# 目标文件夹(D盘下的新文件夹)
target_folder = r'D:\Downloaded_Attachments'
if not os.path.exists(target_folder):
os.makedirs(target_folder)
# 连接到IMAP服务器
mail = imaplib.IMAP4_SSL(imap_url)
mail.login(username, password)
mail.select('inbox') # 选择收件箱
# 获取今天的日期
today = datetime.date.today()
today_start = datetime.datetime.combine(today, datetime.time(0, 0, 0))
search_criteria = f'(SINCE "{today_start.strftime("%d-%b-%Y")}")'
# 执行搜索
type, data = mail.search(None, search_criteria)
mail_ids = data[0].decode().split()
# 下载附件
for mail_id in mail_ids:
_, msg_raw = mail.fetch(mail_id, '(RFC822)')
for response_part in msg_raw:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1])
for part in msg.walk():
if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
file_name = part.get_filename()
if file_name:
# 解码文件名(如果它是编码的)
if isinstance(file_name, tuple):
file_name = decode_header(file_name)[0][0].decode(errors='ignore')
if isinstance(file_name, bytes):
file_name = file_name.decode()
# 防止文件名冲突(添加时间戳)
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
unique_file_name = f"{timestamp}_{file_name}"
# 保存附件
file_path = os.path.join(target_folder, unique_file_name)
with open(file_path, 'wb') as f:
f.write(part.get_payload(decode=True))
print(f"附件已保存:{file_path}")
# 关闭连接
mail.close()
mail.logout()
print(f"所有附件已下载到 {target_folder}")
错误提示:
Traceback (most recent call last):
File "C:/Users/admin/AppData/Local/Programs/Python/Python312/trytry.py", line 53, in <module>
with open(file_path, 'wb') as f:
OSError: [Errno 22] Invalid argument: 'D:\\Downloaded_Attachments\\20240820160000_=?UTF-8?B?MjAyNOW5tDA45pyIMjDml6XkuIrljYjniZ/msbbmsrM=?=\r\n =?UTF-8?B?5oum5rKz6Ze46L6555WM6Ze45rC05oOF5L+h5oGv57uf6K6h6KGoLng=?=\r\n =?UTF-8?B?bHN4?='
错在哪里了呢?