Search code examples
djangoutf-8base64mime

Django - Decoding MIME Header with Base64 and UTF-8


I am creating a web email interface to read IMAP accounts. I'm having problems decoding a certain email header.

I obtain the following From header (specific example from an event email):

('"=?UTF-8?B?QmVubnkgQmVuYXNzaQ==?=" <NOREPLY@NOREPLY.LOCKNLOADEVENTS.COM>', None)

I separate the first part:

=?UTF-8?B?QmVubnkgQmVuYXNzaQ==?=

According to some research, it's aparently a Base64-encoded UTF-8 header.

I tried to decode it using the Base64 decoder:

# Separate sender name from email itself
first_part = header_text[1:header_text.index('" <')]
print "First part:", first_part

import base64
decoded_first_part = base64.urlsafe_b64decode(first_part)
print decoded_first_part

But I obtain a

TypeError: Incorrect padding.

Can anybody help me figure out what's wrong?

Thank you


Solution

  • >>> import base64
    >>> base64.decodestring('QmVubnkgQmVuYXNzaQ==')
    'Benny Benassi'
    

    But you probably want to use a proper IMAP library for doing this stuff.