5

I am having difficulty determining if the body of a text email message is base64 encoded. if it is then use this line of code; making use of jython 2.2.1

dirty=base64.decodebytes(dirty)

else continue as normal.

This is the code I have atm. What line of code will allow me to extract this from the email:

"Content-Transfer-Encoding: base64"

import email, email.Message
import base64

def _get_email_body(self):
    try:
        parts=self._email.get_payload()
        check=parts[0].get_content_type()
        if check=="text/plain":
            part=parts[0].get_payload()
            enc = part[0]['Content-Transfer-Encoding']
            if enc == "base64":
                dirty=base64.decodebytes(dirty)
        elif check=="multipart/alternative":
            part=parts[0].get_payload()
            enc = part[0]['Content-Transfer-Encoding']
            if part[0].get_content_type()=="text/plain":
                dirty=part[0].get_payload()
                if enc == "base64":
                    dirty=base64.decodebytes(dirty)
            else:
                return "cannot obtain the body of the email"
        else:
            return "cannot obtain the body of the email"
        return dirty
    except:
        raise

OKAY this code works now! thanks all

Harry Moreno
  • 10,231
  • 7
  • 64
  • 116
Setori
  • 10,326
  • 11
  • 40
  • 46
  • It would help folks answering you if you could tell us what MIME library object(s) you're using. Are you using Python libraries or Java objects? – Matt Campbell Nov 28 '08 at 02:53
  • okay thanks for the reminder, normally quite good with this! – Setori Nov 28 '08 at 03:32
  • 2
    Possible duplicate of [how can I determine whether an email header is base64 encoded](https://stackoverflow.com/questions/29171919/how-can-i-determine-whether-an-email-header-is-base64-encoded) –  May 25 '17 at 18:02

2 Answers2

6

Try:

enc = msg['Content-Transfer-Encoding']

It's a header so you won't be able to get it looking at the body. You should be able to get at the same place you find out the Subject.

Harley Holcombe
  • 175,848
  • 15
  • 70
  • 63
1

It is a header but you have to get the payload first from the message.

It'll be:

header = msg.get_payload()[0]
header['Content-Transfer-Encoding']

I'm using Python 3

Harry Moreno
  • 10,231
  • 7
  • 64
  • 116
  • It seems that sometimes it's contained in message object, and sometimes it's contained in message.get_payload()[0], as Leon mentioned. Someone can please clarify this? – yoon Apr 23 '20 at 02:51
  • It's a header for each part of the message. So the main body parts (text or html) can be different, as can any attachments. As said above, you have to get the payload for each part, then determine the Content-Transfer-Encoding. I'm surprised it's not been added as a property, but as I'm not clever enough to write the whole email class, I won't criticise too much;-) – JonnyCab Jan 05 '21 at 22:21