How to get decode attachment filename with python

2019-06-21 21:33发布

I use the following code to extract filename of the attachment:

import email.utils

msg = email.message_from_string(self.request.body) # http://docs.python.org/2/library/email.parser.html
for part in msg.walk():
    ctype = part.get_content_type()
    if ctype in ['image/jpeg', 'image/png']:
        image_file = part.get_payload(decode=True)
        image_file_name = part.get_filename()

It works well in many cases, but sometime as image_file_name I get values like =?KOI8-R?B?xsHTLTk2Mi5qcGc=?= or =?UTF-8?B?REkyeTFXMFNMNzAuanBn?=.

How should I handle such cases?

3条回答
地球回转人心会变
2楼-- · 2019-06-21 21:39

You can use decode_header function like this:

from email.header import decode_header

filename = part.get_filename()
if decode_header(filename)[0][1] is not None:
    filename = str(decode_header(filename)[0][0]).decode(decode_header(filename)[0][1])

With Python 3:

from email.message import EmailMessage
from email.header import decode_header


def get_part_filename(msg: EmailMessage):
    filename = msg.get_filename()
    if decode_header(filename)[0][1] is not None:
        filename = decode_header(filename)[0][0].decode(decode_header(filename)[0][1])
    return filename
查看更多
Luminary・发光体
3楼-- · 2019-06-21 21:47

You should look at the three parts separated by '?', and use the first two as instructions for how to treat the third:

The first bit is the character-encoding (KO18-R and UTF-8 in your examples), and the second bit is a 'B' to indicate base64 encoding - Q in it's place would indicate quoted-printable, so you should prepare your code for that as well.

查看更多
Bombasti
4楼-- · 2019-06-21 21:56

Elaborating on @Nikon's response:

from email.header import decode_header

filename = part.get_filename()
fname, charset = decode_header(filename)
if charset:
    filename = fname.decode(charset)
查看更多
登录 后发表回答