1. 程式人生 > 程式設計 >python實現傳送帶附件的郵件程式碼分享

python實現傳送帶附件的郵件程式碼分享

具體程式碼如下:

fromdjango.templateimportloader
fromemail.mime.multipartimportMIMEMultipart
fromemail.mime.textimportMIMEText
fromemail.headerimportHeader
importsmtplib
importtraceback


classSendEmail(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

defmake_html(self,base_html_path,**kwargs):
"""

:parambase_html_path:html模板檔案路徑
:param**kwargs:模板中的引數
:return:
"""
mail_html=loader.render_to_string(
template_name=base_html_path,context={
#"id":tid,**kwargs#傳入模板檔案的資料
}
)
returnmail_html

defadd_attachment(self,file_path):
"""
製作附件
:paramfile_path:
:return:
"""
withopen(file_path,'rb')asf:
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)))#如果檔名中有中文的話需設定
returnatt

defsend_html_email(self,subject,str_to,str_cc,file_path,**kwargs):
"""

:paramhtml:html檔案物件
:paramsubject:郵件主題
: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()
exceptException:
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='[email protected]',password='XXXXX')

    # 構造多元件郵件並完善郵件描述性資訊
    msg = MIMEMultipart()
    msg['Subject'] = '帶附件的郵件-01'
    msg['FROM'] = '[email protected]'
    msg['To'] = '[email protected]'

    # 新增郵件的文字內容
    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='[email protected]',to_addrs='[email protected]')


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,to_addrs=['收件人一','收件人二']) # 多個收件人

到此這篇關於python實現傳送帶附件的郵件程式碼分享的文章就介紹到這了,更多相關利用python實現傳送帶附件的郵件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!