鍍金池/ 問答/Python  網絡安全/ python3發(fā)郵件,附件名稱為中文時出錯

python3發(fā)郵件,附件名稱為中文時出錯

問題描述

我寫了一個發(fā)郵件的類,一切進行的很順利,但是附件名改成中文的時候就出問題了

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

用的是python3*和email包

是了MIMEText、MIMEApplication、MIMEBase都不行

相關代碼

// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)

//下面是MIMEText
att1 = MIMEText(open(v, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
#生成附件的名稱
filename = (v.split("\\"))[-1]
att1["Content-Disposition"] = 'attachment; filename='+filename
#將附件內容插入郵件中
self.message.attach(att1)

//下面是MIMEApplication
xlsxpart = MIMEApplication(open(v, 'rb').read())
basename = (v.split("\\"))[-1]
xlsxpart.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename))
self.message.attach(xlsxpart)

你期待的結果是什么?實際看到的錯誤信息又是什么?

用瀏覽器打開郵箱還能看到一個附件,但是名稱不是正確的,用foxmail打開直接看不到附件。求高手指點。謝謝~~

回答
編輯回答
玄鳥

郵件傳輸附件名不正常中文的。

2017年11月19日 05:29
編輯回答
晚風眠

附件名可以中文,下面是自己以前的一個代碼片段,用make_header

from email.header import  make_header
file_msg = MIMEText(open(file,'rb').read(), 'base64', 'UTF-8')
file_msg["Content-Type"] = 'application/octet-stream;name="%s"'% make_header([(file,'UTF-8')]).encode('UTF-8')
file_msg["Content-Disposition"] = 'attachment;filename= "%s"' % make_header([(file, 'UTF-8')]).encode('UTF-8')
msg.attach(file_msg)
2017年6月4日 07:36