Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get decode attachment filename with python email?

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?

like image 895
LA_ Avatar asked Feb 11 '14 19:02

LA_


1 Answers

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
like image 174
Nikon Avatar answered Sep 21 '22 04:09

Nikon