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

大家好,这里是程序员晚枫,正在all in AI编程实战。
每天要发几十封重复的邮件?
每周要给客户发周报邮件?
今天教你怎么用 python-office 自动发送邮件。
1、发送第一封邮件
1 2 3 4 5 6 7 8
| import office
office.email.send( email='收件人@example.com', title='测试邮件', content='你好,这是程序员晚枫发的测试邮件。' )
|
运行后,收件人会收到一封邮件。
🎉 Done!自动发邮件成功!
2、发送带附件的邮件
1 2 3 4 5 6 7 8 9
| import office
office.email.send( email='收件人@example.com', title='周报', content='这是本周的周报,请查收。', attachment='周报.xlsx' )
|
3、发送HTML格式的邮件
想让邮件更美观?用 HTML 格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import office
html_content = ''' <html> <body> <h2>程序员晚枫的邮件</h2> <p>这是一封<strong>格式化</strong>的邮件。</p> <p>你可以添加图片、超链接等。</p> </body> </html> '''
office.email.send( email='收件人@example.com', title='HTML邮件', content=html_content, type='html' )
|
4、群发邮件
一次发给多个人:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import office
emails = [ '客户1@example.com', '客户2@example.com', '客户3@example.com' ]
for email in emails: office.email.send( email=email, title='产品更新通知', content='尊敬的用户,我们的产品已更新,欢迎体验。' )
print(f'已发送 {len(emails)} 封邮件!')
|
5、实战案例:每日自动发送数据报表
每天早上9点自动发送数据报表:
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
| import office from datetime import date
def send_daily_report(): """发送每日报告""" today = date.today().strftime('%Y-%m-%d') report_file = f'报表_{today}.xlsx' office.email.send( email='领导@example.com', title=f'【日报】{today} 数据报告', content=f'''领导好,
这是 {today} 的数据报告,请查收附件。
祝工作顺利! 程序员晚枫''', attachment=report_file ) print(f'{today} 日报已发送!')
send_daily_report()
|
6、实战案例:批量发送个性化邮件
给每个客户发个性化的邮件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import office
customers = [ {'name': '张三', 'email': 'zhangsan@example.com', 'product': '产品A'}, {'name': '李四', 'email': 'lisi@example.com', 'product': '产品B'}, {'name': '王五', 'email': 'wangwu@example.com', 'product': '产品C'} ]
for customer in customers: office.email.send( email=customer['email'], title=f'尊贵的{customer["name"]},您的{customer["product"]}已发货', content=f'''{customer["name"]} 您好!
您的 {customer["product"]} 已于今日发货,预计3天内送达。
感谢您的支持! 程序员晚枫 ''' )
print(f'已发送 {len(customers)} 封个性化邮件!')
|
7、常见问题
Q:发送失败,提示"认证失败"?
A:需要在邮箱设置里开启 SMTP 服务,获取授权码。QQ邮箱、163邮箱、企业邮箱都支持。
Q:想用企业邮箱发?
A:加上服务器配置:
1 2 3 4 5 6 7 8 9
| office.email.send( email='收件人@example.com', title='标题', content='内容', smtp_server='smtp.你的企业.com', smtp_port=465, smtp_user='your@email.com', smtp_password='your_password' )
|
Q:发送太慢?
A:用多线程并发发送:
1 2 3 4 5
| from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor: for customer in customers: executor.submit(office.email.send, customer['email'], '标题', '内容')
|
8、下讲预告
学会了发邮件,下一讲我们学 邮件收取与附件下载——自动读取邮件、下载附件。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!