Python 邮件附件处理:提取特定字符作为新文件名并保存到桌面
以下是一个示例代码,可以实现处理某个邮件文件夹里邮件附件,下载并提取附件文件内容里字符'11:'后面的字符作为附件新文件名并保存在电脑桌面的功能:
import os
import email
import imaplib
import base64
# 邮件服务器配置
IMAP_SERVER = 'imap.gmail.com'
IMAP_PORT = 993
EMAIL_ACCOUNT = 'your_email_address'
EMAIL_PASSWORD = 'your_email_password'
# 附件保存路径
SAVE_PATH = os.path.expanduser('~/Desktop')
# 连接到邮件服务器
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
mail.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
mail.select('inbox')
# 搜索邮件
typ, data = mail.search(None, 'ALL')
for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
# 处理邮件附件
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename is not None:
# 下载附件
data = part.get_payload(decode=True)
new_filename = filename.split(':')[1] # 获取新文件名
new_filename = os.path.join(SAVE_PATH, new_filename)
# 保存附件文件
with open(new_filename, 'wb') as f:
f.write(data)
# 关闭邮件连接
mail.close()
mail.logout()
需要注意的是,这个示例代码只是一个简单的示例,实际使用时可能需要根据具体的需求进行修改和适配。比如,需要根据具体的邮件服务器和账号信息进行配置,需要根据具体的附件保存路径进行修改等等。
原文地址: https://www.cveoy.top/t/topic/nJ0O 著作权归作者所有。请勿转载和采集!