Python使用smtplib模块发送带附件邮件的完整代码示例

键盘旁的猫
键盘旁的猫
发布时间:2026-10-13 | 5人浏览过
原创

本文提供基于Python smtplib和email模块实现发送带附件邮件的完整代码。通过构建MIMEMultipart消息对象,设置发件人、收件人、主题及正文,并遍历文件列表将附件编码附加至邮件中,最终通过SMTP服务器发送。代码经测试可用,包含服务器配置及调用示例,适合需要自动化邮件通知功能的开发者参考。

本文分享利用Python的smtplib模块实现发送邮件功能的具体代码,供读者参考学习。

#!/usr/bin/env python 
# -*- coding: UTF-8 -*- 
 
from email.mime.multipart import MIMEMultipart 
from email.mime.base import MIMEBase 
from email.mime.text import MIMEText 
  
from email.utils import COMMASPACE,formatdate 
from email import encoders 
  
import os 
  
def send_mail(server, fro, to, subject, text, files=[]):  
  assert type(server) == dict  
  assert type(to) == list  
  assert type(files) == list  
  
  msg = MIMEMultipart()  
  msg['From'] = fro  
  msg['Subject'] = subject  
  msg['To'] = COMMASPACE.join(to) #COMMASPACE==', '  
  msg['Date'] = formatdate(localtime=True)  
  msg.attach(MIMEText(text))  
  
  for f in files:  
    part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data  
    part.set_payload(open(f, 'rb').read())  
    encoders.encode_base64(part)  
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))  
    msg.attach(part)  
  
  import smtplib  
  smtp = smtplib.SMTP(server['name'], server['port'])  
  smtp.ehlo() 
  smtp.starttls() 
  smtp.ehlo()  
  smtp.login(server['user'], server['passwd'])  
  smtp.sendmail(fro, to, msg.as_string())  
  smtp.close() 
   
if __name__=='__main__': 
  server = {'name':'mail.server.com', 'user':'chenxiaowu', 'passwd':'xxxx', 'port':25} 
  fro = 'chenxiaowu@163.com' 
  to = ['xxxx@163.com'] 
  subject = '脚本运行提醒' 
  text = 'mail content' 
  files = ['top_category.txt'] 
  send_mail(server, fro, to, subject, text, files=files) 

参考网络资料整理并修正了部分潜在错误,上述代码已经过调试测试,确认可以正常运行。

以上就是本文的全部内容,希望能为各位的学习带来帮助,同时也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表