1. 程式人生 > >Python3傳送郵件亂碼問題:add_header(self,_name,_value,**_params)方法

Python3傳送郵件亂碼問題:add_header(self,_name,_value,**_params)方法

在傳送附件時如果是中文名的檔案,則會出現亂碼。

可以使用: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)