在傳送附件時如果是中文名的文件,則會出現亂碼。
可以使用:msg.add_header('content-disposition', 'attachment',filename=('utf-8', '', 我.txt))
最後一個參數:params:可以直接寫成文件名,也可寫成路徑加文件名,qq郵箱會自動過濾掉路徑,留下文件名
而163郵箱則不會過濾掉路徑,顯示出來整個路徑作爲文件名,這時可以採用把文件名從路徑中截取出來。
1)fileName=r'C:\Users\10135\Desktop\宣傳.png'
msg.add_header('content-disposition', 'attachment',filename=('utf-8', '', '宣傳.txt'))
2)fileName=r'C:\Users\10135\Desktop\宣傳.png'
msgImage.add_header("Content-Disposition", "attachment",filename=("gbk", "", fileName.split("\\")[-1]))
3)使用basename()函數
import os.
path
filePath
=
"K:/Project/FilterDriver/DriverCodes/hello.txt"
msgImage.add_header("Content-Disposition", "attachment",filename=os.path
.basename
(
filePath
)))
def add_header(self, _name, _value, **_params):
"""Extended header setting.
name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added. If a
parameter value contains non-ASCII characters it can be specified as a
three-tuple of (charset, language, value), in which case it will be
encoded according to RFC2231 rules. Otherwise it will be encoded using
the utf-8 charset and a language of ''.
Examples:
msg.add_header('content-disposition', 'attachment', filename='bud.gif')
msg.add_header('content-disposition', 'attachment',
filename=('utf-8', '', Fußballer.ppt'))
msg.add_header('content-disposition', 'attachment',
filename='Fußballer.ppt'))
"""
parts = []
for k, v in _params.items():
if v is None:
parts.append(k.replace('_', '-'))
else:
parts.append(_formatparam(k.replace('_', '-'), v))
if _value is not None:
parts.insert(0, _value)
self[_name] = SEMISPACE.join(parts)