TheEditor
TheEditor

Reputation: 474

Test for base64 encoding with python

I'm having some trouble with this bit of python.

def get_msg( message ):
    if not message.is_multipart():
            if "base64" in str(message.get_payload()):
                    return base64.decodestring(str(message.get_payload()))
    return message.get_payload()
    return '\n\n'.join( [base64.decodestring(str(m)) for m in message.get_payload()] )

Lines 3 and 4 to be exact. If the message is NOT multipart I need to test to see if it is base64 encoded. Exchange likes to do this sometimes and it creates an issue when I encrypt it.

As you see by the unelegant bit after that I can deal with it for attachments but how do I test for the base64 encoding? I tried if/in. I'm not sure I'm doing it right though.

Upvotes: 0

Views: 671

Answers (1)

mata
mata

Reputation: 69042

You need to look at the Content-Transfer-Encoding header to see if the payload is base64 encoded, so:

if message['Content-Transfer-Encoding'] == 'base64':
    # ...

But the simpler solution would probably be to use

message.get_payload(decode=True)

That decodes the payload if it's encoded, and in addition also works if the payload is quoted pritntable encoded instead of base64.

Upvotes: 2

Related Questions