为什么我的代码老是出错?
我写了个下载邮箱附件的代码,
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?='
错在哪里了呢?
相关推荐
Native-Regex:一套用于将正则表达式构建到源代码和Rust宏中的工具
本地正则表达式一个工具库,用于将Regex引擎编译为编程语言源代码。为什么? 正则表达式非常有用,没有它们,字符串处理最多是困难的,最坏的情况下容易出错和令人沮丧。 但是,它们确实会带来很大的性能开销
为什么你的代码总是出错?或许你忽视了这些细节!
大家好,今天咱们聊一个程序员常常面临的问题——代码出错!很多时候,我们以为自己已经做得很完美,写的代码也非常干净简洁,但总是出现莫名其妙的错误。你有没有觉得自己的代码像是一个精密的机器,按照你设定的步骤应该顺利运行,但总是出现各种“意外”,甚至是那些你自己都没法理解的bug?今天,就让我带着一颗爆笑的心情,一起扒一扒代码中常见的那些细节问题,看看是哪些“阴魂不散”的小细节,悄悄坑了我们!别担心,我们会从头到尾一起调侃这些坑,同时给出实际的代码案例和讲解。你还等什么?
快速解决boost库链接出错的问题(分享)
原因解释-------------为什么需要设置 LD_LIBRARY_PATH 环境变量?
puppet-hiera-deep-merge:人偶的hiera_hash包装器,用于按需深度合并
人偶-希拉按需深度合并为什么 ? 1.2引入了,这是在中管理内容的主要增强功能。 但是合并行为是Hiera中的全局设置,因此迁移大型p代码库可能会容易出错。 该模块提供了一个名为hiera_hash
爱站seo工具包安装出错解决办法.docx
首先,需要了解为什么会出现这种错误。其实这种错误是由于安装权限不足造成的。在Win8系统中,安装msi安装包时,经常会出现代码为2502、2503的错误。


