利用python实现发送带附件的邮件
2023-03-20 14:44:16 时间
具体代码如下:
(相关推荐:python基础教程)
from django.template import loader from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header import smtplib import traceback class SendEmail(object): """ 发送html邮件 """ def __init__(self, mail_host, mail_port, mail_user, mail_pass, sender, to_list_email): # 创建邮件对象 self.msg = MIMEMultipart() # 邮箱服务地址 self.mail_host = mail_host # 邮箱端口号 self.mail_port = mail_port # 邮箱账号 self.mail_user = mail_user # 密码 self.mail_pass = mail_pass # 发送人 self.sender = sender # 收件人邮箱列表 self.to_list_email = to_list_email def make_html(self, base_html_path, **kwargs): """ :param base_html_path: html模板文件路径 :param **kwargs: 模板中的参数 :return: """ mail_html = loader.render_to_string( template_name=base_html_path, context={ # "id": tid, **kwargs # 传入模板文件的数据 } ) return mail_html def add_attachment(self, file_path): """ 制作附件 :param file_path: :return: """ with open(file_path, 'rb') as f: content = f.read() att = MIMEText(content, _subtype='plain', _charset='utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename=task_report.docx' att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "{}".format(filename))) # 如果文件名中有中文的话需设置 return att def send_html_email(self, base_html_path, subject, str_to, str_cc, file_path, **kwargs): """ :param html: html文件对象 :param subject: 邮件主题 :return: """ html = self.make_html(base_html_path, **kwargs) self.msg.attach(MIMEText(str(html), 'html')) self.msg['from'] = Header('安全测试平台', 'utf-8') self.msg['Subject'] = Header(subject, 'utf-8') self.msg["Accept-Language"] = "zh-CN" self.msg["Accept-Charset"] = "ISO-8859-1,utf-8" self.msg['to'] = str_to # 发送人 str self.msg['cc'] = str_cc # 抄送人 str # 添加附件 att = self.add_attachment(file_path) self.msg.attach(att) # 发送邮件 try: server = smtplib.SMTP() server.connect(self.mail_host, self.mail_port) server.login(self.mail_user, self.mail_pass) server.sendmail(self.sender, self.to_list_email, self.msg.as_string()) server.quit() except Exception: print(traceback.format_exc())
相关文章
- PyCharm vs VSCode,是时候改变你的 IDE 了!
- 一个用于大规模连续测试的开源解决方案
- 学C语言好还是Python好?
- Python人工智能速成班泛滥 专家:小学生都能学
- 调包侠神器2.0发布,Python机器学习模型搭建只需要几行代码
- 五大代码异味:你需要提高警惕了!
- 分分钟甩Word几条街,Python编辑公式竟可以如此简单
- IEEE Spectrum 评估的最流行语言是 Python
- Python继续霸榜,上古语言Cobol获关注,IEEE2020编程语言榜单揭晓
- 蚂蚁王益:Go+ 可有效补全 Python 的不足
- 2020年优秀的Python代码编辑器
- 6月份Github上热门的Python开源项目
- 学习Python两年,我的人生轨迹发生了怎样的变化?
- 三歪手把手教你干掉if else
- 1个小技巧,让你的Python代码运行效率提升17倍
- VS Code中更强大的Python扩展来了!Pyright可以删了
- 1行代码实现Python数据分析:图表美观清晰,自带对比功能丨开源
- 口述完SpringMVC的执行流程后,面试官说兄弟,你是培训的吧!
- YOLOv5来了!基于PyTorch,体积比YOLOv4小巧90%,速度却超2倍
- 哈工大、哈工程MATLAB被禁或严重影响高校科研,Python和Octave可替代