
👉 项目官网:https://www.python-office.com/ 👈

大家好,这里是程序员晚枫,正在all in AI编程实战。
每天要下载邮件里的附件?
客户发来的文件要一个个保存?
今天教你怎么用 python-office 自动收取邮件并下载附件。
1、读取最新邮件
1 2 3 4 5 6 7 8 9 10 11
| import office
emails = office.email.read(lastest=5)
for email in emails: print(f'发件人: {email["from"]}') print(f'标题: {email["subject"]}') print(f'时间: {email["date"]}') print(f'内容: {email["content"]}') print('---')
|
运行后,会打印出最近 5 封邮件的内容。
2、自动下载附件
1 2 3 4 5 6 7
| import office
office.email.download( save_path='C:\\邮件附件', lastest=10 )
|
运行后,所有邮件的附件都会下载到指定文件夹。
3、按发件人筛选
只想看某个人的邮件?
1 2 3 4 5 6 7 8 9 10 11 12
| import office
emails = office.email.read( sender='客户@example.com', lastest=10 )
for email in emails: print(f'标题: {email["subject"]}') print(f'内容: {email["content"]}') print('---')
|
4、只下载特定类型的附件
1 2 3 4 5 6 7 8
| import office
office.email.download( save_path='C:\\Excel附件', lastest=20, file_type='.xlsx' )
|
5、实战案例:自动归档客户邮件
把每个客户的邮件归档到对应文件夹:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import office import os import re
def archive_emails(): """归档邮件到对应文件夹""" emails = office.email.read(lastest=50) for email in emails: sender = email['from'] folder = os.path.join('邮件归档', sender.replace('@', '_at_')) os.makedirs(folder, exist_ok=True) filename = f"{email['date'].replace(':', '-')}_{email['subject']}.txt" filepath = os.path.join(folder, filename) with open(filepath, 'w', encoding='utf-8') as f: f.write(f"发件人: {email['from']}\n") f.write(f"标题: {email['subject']}\n") f.write(f"时间: {email['date']}\n") f.write(f"\n内容:\n{email['content']}") print(f'已归档: {email["subject"]}')
archive_emails()
|
6、实战案例:自动下载客户订单附件
每天自动下载订单邮件的附件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import office import os from datetime import date
def download_orders(): """下载订单邮件附件""" today = date.today().strftime('%Y-%m-%d') save_path = f'订单_{today}' os.makedirs(save_path, exist_ok=True) emails = office.email.read( subject='订单', lastest=20 ) count = 0 for email in emails: office.email.download( save_path=save_path, email_id=email['id'], file_type='.xlsx' ) count += 1 print(f'今日共下载 {count} 个订单附件')
download_orders()
|
7、常见问题
Q:读取邮件报错?
A:需要在邮箱设置里开启 IMAP 服务,获取授权码。
Q:下载的附件名是乱码?
A:用 decode_filename=True 参数可以解决中文文件名乱码问题。
Q:想读取指定日期的邮件?
A:
1 2 3 4
| emails = office.email.read( start_date='2024-01-01', end_date='2024-01-31' )
|
8、下讲预告
学会了邮件处理,下一讲我们学 OCR文字识别——从图片里提取文字。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!