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)

猜你喜欢

转载自blog.csdn.net/Winnycatty/article/details/84309847
今日推荐