本篇文章給大家分享的是有關(guān)python實(shí)現(xiàn)發(fā)送帶附件的郵件,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
創(chuàng)新互聯(lián)公司云計(jì)算的互聯(lián)網(wǎng)服務(wù)提供商,擁有超過13年的服務(wù)器租用、成都移動(dòng)機(jī)房托管、云服務(wù)器、虛擬主機(jī)、網(wǎng)站系統(tǒng)開發(fā)經(jīng)驗(yàn),已先后獲得國家工業(yè)和信息化部頒發(fā)的互聯(lián)網(wǎng)數(shù)據(jù)中心業(yè)務(wù)許可證。專業(yè)提供云主機(jī)、虛擬主機(jī)、空間域名、VPS主機(jī)、云服務(wù)器、香港云服務(wù)器、免備案服務(wù)器等。具體代碼如下:
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())
以上就是python實(shí)現(xiàn)發(fā)送帶附件的郵件,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道。