python实现发送带附件的邮件代码分享
作者:FXL 时间:2021-11-24 12:28:30
具体代码如下:
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())
内容扩展:
实例二:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
"""
发送带附件邮件的完整代码
"""
class HandleEmail():
def handle_email(self):
# step1 连接smtp服务器并登陆
smtp = smtplib.SMTP_SSL(host='smtp.qq.com', port=465)
smtp.login(user='XXXXX@qq.com', password='XXXXX')
# 构造多组件邮件并完善邮件描述性信息
msg = MIMEMultipart()
msg['Subject'] = '带附件的邮件-01'
msg['FROM'] = 'XXXXXX@qq.com'
msg['To'] = 'XXXXX@163.com'
# 添加邮件的文本内容
text = MIMEText(_text='这是邮件正文的内容', _charset='UTF8')
msg.attach(text)
# 添加附件和附件header
with open(file=r'XXXXXXXX\report.html', mode='rb') as f:
content = f.read()
attachment = MIMEApplication(_data=content)
attachment.add_header('content-disposition', 'attachment', filename='report.html')
msg.attach(attachment)
# 发送邮件
smtp.send_message(msg=msg, from_addr='XXXXXXX@qq.com', to_addrs='XXXXX@163.com')
if __name__ == '__main__':
e_mail = HandleEmail()
e_mail.handle_email()
使用创建好的smtp对象发送邮件,需要把上面编辑好的msg作为参数传入,然后填写收发件人,如果有多个收件人,以列表的形式传入参数
smtp.send_message(msg=msg,from_addr='',to_addrs='') # 单个收件人
smtp.send_message(msg=msg,from_addr='',to_addrs=['收件人一','收件人二']) # 多个收件人
来源:https://www.py.cn/toutiao/20166.html
标签:python,附件邮件
0
投稿
猜你喜欢
laravel接管Dingo-api和默认的错误处理方式
2023-11-21 23:29:37
python中利用Future对象回调别的函数示例代码
2021-09-28 13:03:43
javascript面向对象编程(四)
2008-03-07 14:20:00
Vue2子组件绑定 v-model,实现父子组件通信方式
2024-05-02 17:04:13
python字典多条件排序方法实例
2023-06-22 03:43:07
Sql学习第一天——SQL 练习题(建表/sql语句)
2024-01-22 05:44:39
OpenCV使用KNN完成OCR手写体识别
2022-02-17 12:16:21
python批量修改图片后缀的方法(png到jpg)
2022-01-19 19:09:24
详解Python中的Descriptor描述符类
2021-10-16 10:10:35
使用babel-plugin-import 实现自动按需引入方式
2024-04-27 16:00:42
JavaScript实现仿淘宝商品购买数量的增减效果
2024-06-07 15:26:09
Python数字/字符串补零操作实例代码
2021-07-13 03:16:57
python3爬虫中多线程的优势总结
2023-05-15 02:41:07
Python解析并读取PDF文件内容的方法
2021-07-13 20:06:21
各种SQL语句速查手册
2007-09-27 19:31:00
Python 数据科学 Matplotlib图库详解
2022-09-24 15:18:34
Python爬虫+Tkinter制作一个翻译软件的示例
2023-12-14 07:22:42
Python面试之os.system()和os.popen()的区别详析
2023-09-14 18:15:39
python字典排序实例详解
2021-10-12 12:12:02
MySql多表查询 事务及DCL
2024-01-29 04:55:28