這篇文章將為大家詳細(xì)講解有關(guān)利用python實(shí)現(xiàn)發(fā)送帶附件的郵件,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
成都一家集口碑和實(shí)力的網(wǎng)站建設(shè)服務(wù)商,擁有專業(yè)的企業(yè)建站團(tuán)隊(duì)和靠譜的建站技術(shù),十載企業(yè)及個(gè)人網(wǎng)站建設(shè)經(jīng)驗(yàn) ,為成都上1000家客戶提供網(wǎng)頁(yè)設(shè)計(jì)制作,網(wǎng)站開(kāi)發(fā),企業(yè)網(wǎng)站制作建設(shè)等服務(wù),包括成都營(yíng)銷型網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計(jì),同時(shí)也為不同行業(yè)的客戶提供網(wǎng)站制作、做網(wǎng)站的服務(wù),包括成都電商型網(wǎng)站制作建設(shè),裝修行業(yè)網(wǎng)站制作建設(shè),傳統(tǒng)機(jī)械行業(yè)網(wǎng)站建設(shè),傳統(tǒng)農(nóng)業(yè)行業(yè)網(wǎng)站制作建設(shè)。在成都做網(wǎng)站,選網(wǎng)站制作建設(shè)服務(wù)商就選創(chuàng)新互聯(lián)公司。具體代碼如下:
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): """ 發(fā)送html郵件 """ def __init__(self, mail_host, mail_port, mail_user, mail_pass, sender, to_list_email): # 創(chuàng)建郵件對(duì)象 self.msg = MIMEMultipart() # 郵箱服務(wù)地址 self.mail_host = mail_host # 郵箱端口號(hào) self.mail_port = mail_port # 郵箱賬號(hào) self.mail_user = mail_user # 密碼 self.mail_pass = mail_pass # 發(fā)送人 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: 模板中的參數(shù) :return: """ mail_html = loader.render_to_string( template_name=base_html_path, context={ # "id": tid, **kwargs # 傳入模板文件的數(shù)據(jù) } ) 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))) # 如果文件名中有中文的話需設(shè)置 return att def send_html_email(self, base_html_path, subject, str_to, str_cc, file_path, **kwargs): """ :param html: html文件對(duì)象 :param subject: 郵件主題 :return: """ html = self.make_html(base_html_path, **kwargs) self.msg.attach(MIMEText(str(html), 'html')) self.msg['from'] = Header('安全測(cè)試平臺(tái)', '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 # 發(fā)送人 str self.msg['cc'] = str_cc # 抄送人 str # 添加附件 att = self.add_attachment(file_path) self.msg.attach(att) # 發(fā)送郵件 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())