在 Python 中发送电子邮件是自动化办公和系统监控的常用功能。以下是 5 种邮件发送方法的详细实现,涵盖基础发送、附件添加、HTML 内容等场景:
(图片来源网络,侵删)
关键点:
使用 SMTP_SSL 加密连接(端口通常为465)主流邮箱SMTP服务器:QQ邮箱:smtp.qq.com163邮箱:smtp.163.comGmail:smtp.gmail.com2. 发送HTML格式邮件from email.mime.multipart import MIMEMultiparthtml_content = """<html> <body> <h1 style="color:red;">重要通知</h1> <p>您的订单已发货!</p> <a href="https://example.com">点击查看详情</a> </body></html>"""msg = MIMEMultipart()msg.attach(MIMEText(html_content, 'html', 'utf-8'))msg['Subject'] = 'HTML邮件测试'# 其余配置同基础版...3. 添加附件(图片/文件)from email.mime.application import MIMEApplicationmsg = MIMEMultipart()msg.attach(MIMEText('请查收附件', 'plain'))# 添加Excel附件with open('report.xlsx', 'rb') as f: attach = MIMEApplication(f.read(), _subtype="xlsx") attach.add_header('Content-Disposition', 'attachment', filename='月度报告.xlsx') msg.attach(attach)# 添加图片(嵌入正文)with open('logo.png', 'rb') as f: img = MIMEImage(f.read()) img.add_header('Content-ID', '<logo>') msg.attach(img) msg.attach(MIMEText('<img src="cid:logo">', 'html')) # HTML引用图片4. 使用第三方库(yagmail)简化版操作(需安装:pip install yagmail):
import yagmailyag = yagmail.SMTP(user='your_email@example.com', password='your_password', host='smtp.example.com')contents = [ '邮件正文内容', '可多个部分自动拼接', {'附件': '/path/to/file.pdf'}]yag.send(to='recipient@example.com', subject='主题', contents=contents)5. 企业邮箱/Exchange服务(OAuth2认证)from exchangelib import Credentials, Accountcredentials = Credentials('username@company.com', 'password')account = Account('username@company.com', credentials=credentials, autodiscover=True)# 发送邮件account.send_mail( subject='会议通知', body='明天10点会议室A', to_recipients=['colleague@company.com'])6. 常见问题解决方案问题1:SMTP认证错误检查是否开启SMTP服务(邮箱设置中)使用应用专用密码(如Gmail需16位密码)尝试降低安全等级(部分邮箱需允许"不太安全的应用")问题2:附件乱码filename = ('中文文件.pdf', 'utf-8') # 指定编码attach.add_header('Content-Disposition', 'attachment', filename=filename)问题3:发送速度慢复用SMTP连接:server = smtplib.SMTP_SSL(...) server.sendmail(...) # 多次发送 server.quit() # 最后关闭7. 安全建议不要硬编码密码:import ospassword = os.getenv('EMAIL_PASSWORD') # 从环境变量读取使用加密连接:
优先选择 SMTP_SSL(端口465)或 starttls()(端口587):server = smtplib.SMTP(smtp_server, 587)server.starttls()8. 完整案例:错误监控邮件import tracebackdef error_monitor(): try: # 模拟错误代码 1 / 0 except Exception: error_msg = traceback.format_exc() msg = MIMEMultipart() msg.attach(MIMEText(f"程序报错:\n{error_msg}", 'plain')) msg['Subject'] = '系统异常警报' # 添加错误日志附件 with open('error.log', 'w') as f: f.write(error_msg) with open('error.log', 'rb') as f: msg.attach(MIMEText(f.read(), 'base64', 'utf-8')) # 发送代码...9. 扩展学习批量发送(邮件合并):recipients = ['a@test.com', 'b@test.com']for to in recipients: yag.send(to=to, subject='个性化主题', contents=f'{to}的专属内容')定时发送(结合 schedule 库):
import scheduleschedule.every().day.at("09:00").do(send_daily_report)邮件解析(接收邮件):
import imaplibmail = imaplib.IMAP4_SSL('imap.example.com')mail.login(user, password)mail.select('inbox')掌握邮件发送后,你可以实现:✅ 自动化报表发送✅ 系统异常报警✅ 批量通知推送✅ 用户注册验证
转载请注明来自极限财经,本文标题:《qq邮箱可以发送163邮箱吗(python入门到脱坑经典案例邮件发送)》
还没有评论,来说两句吧...