Produce the IMAP formatted String for the BodyStructure of a pre-parsed MimeMessage
TODO handle extension elements - Content-disposition, Content-Language and other parameters.
426328
String parseBodyStructure(boolean includeExtension) {
        try {
            String fields = parseBodyFields();
            StringBuilder buf = new StringBuilder();
            buf.append(LB);
            if (primaryType.equalsIgnoreCase("Text")) {
                buf.append("\"TEXT\" \"");
                buf.append(secondaryType.toUpperCase());
                buf.append("\" ");
                buf.append(fields);
                buf.append(' ');
                buf.append(lineCount);

                // is:    * 1 FETCH (BODYSTRUCTURE ("Text" "plain" NIL NIL NIL NIL    4  -1))
                // wants: * 1 FETCH (BODYSTRUCTURE ("text" "plain" NIL NIL NIL "8bit" 6  1  NIL NIL NIL))
                // or:    * 1 FETCH (BODYSTRUCTURE ("text" "plain" NIL NIL NIL "7bit" 28 1 NIL NIL NIL))

            } else if (primaryType.equalsIgnoreCase(MESSAGE) && secondaryType.equalsIgnoreCase("rfc822")) {
                buf.append("\"MESSAGE\" \"RFC822\" ");
                buf.append(fields).append(SP);
//                setupLogger(parts[0]); // reset transient logger
                buf.append(parts[0].getEnvelope()).append(SP);
                buf.append(parts[0].getBodyStructure(false)).append(SP);
                buf.append(lineCount);
            } else if (primaryType.equalsIgnoreCase(MULTIPART)) {
                for (MailMessageAttributes part : parts) {
//                    setupLogger(parts[i]); // reset transient getLogger()
                    buf.append(part.getBodyStructure(includeExtension));
                }
                buf.append(SP + Q).append(secondaryType).append(Q);
            } else {
                //1. primary type -------
                buf.append('\"');
                buf.append(primaryType.toUpperCase());
                buf.append('\"');
                //2. sec type -------
                buf.append(" \"");
                buf.append(secondaryType.toUpperCase());
                buf.append('\"');
                //3. params -------
                buf.append(' ');
                getParameters(buf);
                //4. body id -------
                buf.append(' ');
                if (null != contentID ) {
                    buf.append(Q).append(contentID).append(Q);
                } else {
                    buf.append(NIL);
                }
                //5. content desc -------
                buf.append(' ');
                if (null != contentDesc) {
                    buf.append('\"');
                    buf.append(contentDesc);
                    buf.append('\"');
                } else {
                    buf.append(NIL);
                }
                //6. encoding -------
                buf.append(' ');
                if (null != contentEncoding) {
                    buf.append('\"');
                    buf.append(contentEncoding);
                    buf.append('\"');
                } else {
                    buf.append(NIL);
                }
                //7. size -------
                buf.append(' ');
                buf.append(size);
            }

            if (includeExtension) {
                //extension is different for multipart and single parts
                if (primaryType.equalsIgnoreCase(MULTIPART)) {
                    //8. ext1 params -------
                    buf.append(' ');
                    getParameters(buf);
                    //9. ext2 disposition -------
                    buf.append(' ');
                    if (null != contentDisposition) {
                        buf.append(contentDisposition);
                    } else {
                        buf.append(NIL);
                    }
                    //10. ext3 language -------
                    buf.append(' ');
                    buf.append(NIL);
                } else {
                    // ext1 md5 -------
                    buf.append(' ');
                    buf.append(NIL);
                    // ext2 disposition -------
                    buf.append(' ');
                    if (null != contentDisposition) {
                        buf.append(contentDisposition);
                    } else {
                        buf.append(NIL);
                    }
                    //ext3 language -------
                    buf.append(' ');
                    buf.append(NIL);
                }
            }

            buf.append(RB);
            return buf.toString();
        } catch (Exception e) {
            throw new IllegalStateException("Can not parse body structure", e);
        }
    }
594298
private static MimeBodyPart createBodyPart(byte[] data, String type, String filename) throws MessagingException {
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setFileName(filename);
        ByteArrayDataSource source = new ByteArrayDataSource(data, type);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setHeader("Content-ID", createContentID(filename));
        attachmentPart.setDisposition(MimeBodyPart.INLINE);
        return attachmentPart;
    }
952541
protected function _prepareBody()
    {
        // According to RFC2616, a TRACE request should not have a body.
        if ($this->method == self::TRACE) {
            return '';
        }

        if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) {
            return $this->raw_post_data;
        }
        // If mbstring overloads substr and strlen functions, we have to
        // override it's internal encoding
        if (function_exists('mb_internal_encoding') &&
           ((int) ini_get('mbstring.func_overload')) & 2) {

            $mbIntEnc = mb_internal_encoding();
            mb_internal_encoding('ASCII');
        }

        // If we have raw_post_data set, just use it as the body.
        if (isset($this->raw_post_data)) {
            $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
            if (isset($mbIntEnc)) {
                mb_internal_encoding($mbIntEnc);
            }

            return $this->raw_post_data;
        }

        $body = '';

        // If we have files to upload, force enctype to multipart/form-data
        if (count ($this->files) > 0) {
            $this->setEncType(self::ENC_FORMDATA);
        }

        // If we have POST parameters or files, encode and add them to the body
        if (count($this->paramsPost) > 0 || count($this->files) > 0) {
            switch($this->enctype) {
                case self::ENC_FORMDATA:
                    // Encode body as multipart/form-data
                    $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
                    $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");

                    // Encode all files and POST vars in the order they were given
                    foreach ($this->body_field_order as $fieldName=>$fieldType) {
                        switch ($fieldType) {
                            case self::VTYPE_FILE:
                                foreach ($this->files as $file) {
                                    if ($file['formname']===$fieldName) {
                                        $fhead = array(self::CONTENT_TYPE => $file['ctype']);
                                        $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
                                    }
                                }
                                break;
                            case self::VTYPE_SCALAR:
                                if (isset($this->paramsPost[$fieldName])) {
                                    if (is_array($this->paramsPost[$fieldName])) {
                                        $flattened = self::_flattenParametersArray($this->paramsPost[$fieldName], $fieldName);
                                        foreach ($flattened as $pp) {
                                            $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
                                        }
                                    } else {
                                        $body .= self::encodeFormData($boundary, $fieldName, $this->paramsPost[$fieldName]);
                                    }
                                }
                                break;
                        }
                    }

                    $body .= "--{$boundary}--\r\n";
                    break;

                case self::ENC_URLENCODED:
                    // Encode body as application/x-www-form-urlencoded
                    $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
                    $body = http_build_query($this->paramsPost, '', '&');
                    break;

                default:
                    if (isset($mbIntEnc)) {
                        mb_internal_encoding($mbIntEnc);
                    }

                    /** @see Zend_Http_Client_Exception */

                    throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
                        " Please use Zend_Http_Client::setRawData to send this kind of content.");
                    break;
            }
        }

        // Set the Content-Length if we have a body or if request is POST/PUT
        if ($body || $this->method == self::POST || $this->method == self::PUT) {
            $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
        }

        if (isset($mbIntEnc)) {
            mb_internal_encoding($mbIntEnc);
        }

        return $body;
    }
923629
def text(self, text):
        '''
        
        '''

        if text:
            if not isinstance(text, str):
                text = _pformat(text)
            text += '\n\n'
            self.m(
                'add text to mail',
                more=dict(len=len(text))
            )
            self.__message.attach(_MIMEText(text, 'plain', 'UTF-8'))
719799
def to_mime_message(self):
        """"""
        msg = MIMEMultipart('alternative')
        msg['Subject'] = self._header(self._subject or '')

        msg['From'] = self._encoded(self._addrs_to_header([self._from]))
        msg['To'] = self._encoded(self._addrs_to_header(self._to))

        if self._cc:
            msg['CC'] = self._addrs_to_header(self._cc)

        if self._headers:
            for key, value in self._headers.items():
                msg[key] = self._header(value)

        for part in self._parts:
            type_maj, type_min = part[0].split('/')
            if type_maj == 'text' and type_min in ('html', 'plain'):
                msg.attach(MIMEText(part[1], type_min, self._charset))
            else:
                msg.attach(part[1])

        return msg
433781
def prepare(self, mime):
        
        for key in self:
            if key == 'Bcc' or key == 'Resent-Bcc':
                continue
            del mime[key]
            # Python 3.* email's compatibility layer will handle
            # unicode field values in proper way but Python 2
            # won't (it will encode not only additional field
            # values but also all header values)
            parsed_header, additional_fields = parse_header(
                self[key] if IS_PY3 else
                self[key].encode("utf-8")
            )
            mime.add_header(key, parsed_header, **additional_fields)
1009801
protected function decodeBody()
    {
        if(is_object($this->message)){
            foreach ($this->message->types as $typeMessage) {
                if(is_object($this->message->$typeMessage)){
                    switch ($this->message->$typeMessage->structure->encoding) {
                        case 3:
                            $this->message->$typeMessage->body = imap_base64($this->message->$typeMessage->body);
                            break;
                        case 4:
                            $this->message->$typeMessage->body = imap_qprint($this->message->$typeMessage->body);
                            break;
                    }
                }

                if(is_object($this->message->$typeMessage)){
                    if ($this->message->$typeMessage->charset) {
                        $this->message->$typeMessage->body = $this->convertToUtf8($this->message->$typeMessage->body, $this->message->$typeMessage->charset);
                    }
                }
            }
        }
    }
624866
function createHtmlDocument (message) {
  var body = escapeHtml(message)
    .replace(NEWLINE_REGEXP, '<br>')
    .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;')

  return '<!DOCTYPE html>\n' +
    '<html lang="en">\n' +
    '<head>\n' +
    '<meta charset="utf-8">\n' +
    '<title>Error</title>\n' +
    '</head>\n' +
    '<body>\n' +
    '<pre>' + body + '</pre>\n' +
    '</body>\n' +
    '</html>\n'
}
317621
private static JsJmsMessage decodeTextBody(String body) throws MessageDecodeFailedException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "decodeTextBody");
        JsJmsTextMessage result = new JsJmsTextMessageImpl(MfpConstants.CONSTRUCTOR_NO_OP);
        if (body != null) {
            result.setText(URLDecode(body));
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "decodeTextBody");
        return result;
    }
927677
def get_mime_message(self):
        
        message = MIMEText(
            "<html>" +
            self.get_email_header() +
            get_email_content(self.content_file) +
            self.get_email_footer() +
            "</html>", "html"
        )
        message["subject"] = self.email_subject
        return message
1311678
def prepare_attachments(attachment):
    
    if isinstance(attachment, tuple):
        result = {"Name": attachment[0], "Content": attachment[1], "ContentType": attachment[2]}
        if len(attachment) == 4:
            result["ContentID"] = attachment[3]
    elif isinstance(attachment, MIMEBase):
        payload = attachment.get_payload()
        content_type = attachment.get_content_type()
        # Special case for message/rfc822
        # Even if RFC implies such attachments being not base64-encoded,
        # Postmark requires all attachments to be encoded in this way
        if content_type == "message/rfc822" and not isinstance(payload, str):
            payload = b64encode(payload[0].get_payload(decode=True)).decode()
        result = {
            "Name": attachment.get_filename() or "attachment.txt",
            "Content": payload,
            "ContentType": content_type,
        }
        content_id = attachment.get("Content-ID")
        if content_id:
            if content_id.startswith("<") and content_id.endswith(">"):
                content_id = content_id[1:-1]
            if (attachment.get("Content-Disposition") or "").startswith("inline"):
                content_id = "cid:%s" % content_id
            result["ContentID"] = content_id
    elif isinstance(attachment, str):
        content_type = guess_content_type(attachment)
        filename = os.path.basename(attachment)
        with open(attachment, "rb") as fd:
            data = fd.read()
        result = {"Name": filename, "Content": b64encode(data).decode("utf-8"), "ContentType": content_type}
    else:
        result = attachment
    return result
802048
def get_body(message):
    
    try:
        sm = str(message)
        body_start = sm.find('iamunique', sm.find('iamunique')+1)
        body_start = sm.find('Content-Transfer-Encoding', body_start+1)
        body_start = sm.find('\n', body_start+1)+1

        body_end = sm.find('From: ', body_start + 1)
        if body_end == -1:
            body_end = sm.find('iamunique', body_start + 1)
            body_end = sm.find('\n', body_end - 25)
        body = sm[body_start:body_end]

        body = body.replace("=20\n", "")
        body = body.replace("=FC", "ü")
        body = body.replace("=F6", "ö")
        body = body.replace("=84", "\"")
        body = body.replace("=94", "\"")
        body = body.replace("=96", "-")
        body = body.replace("=92", "\'")
        body = body.replace("=93", "\"")
        body = body.replace("=E4", "ä")
        body = body.replace("=DF", "ss")
        body = body.replace("=", "")
        body = body.replace("\"", "")
        body = body.replace("\'", "")
    except:
        body = None

    return body
476582
def extract_from_plain(msg_body):
    """"""
    stripped_text = msg_body

    delimiter = get_delimiter(msg_body)
    msg_body = preprocess(msg_body, delimiter)
    # don't process too long messages
    lines = msg_body.splitlines()[:MAX_LINES_COUNT]
    markers = mark_message_lines(lines)
    lines = process_marked_lines(lines, markers)

    # concatenate lines, change links back, strip and return
    msg_body = delimiter.join(lines)
    msg_body = postprocess(msg_body)
    return msg_body
636057
def fetch_plaintext(self, msg_nums):
        
        if not msg_nums:
            raise Exception("Invalid Message Number!")

        return self.__imap_fetch_content_type(msg_nums, self.PLAIN)
356364
def get_body(self):
        """"""

        if self.is_multipart():
            # get the plain text version only
            text_parts = [part
                          for part in typed_subpart_iterator(self,
                                                             'text',
                                                             'plain')]
            body = []
            for part in text_parts:
                charset = get_charset(part, get_charset(self))
                body.append(unicode(part.get_payload(decode=True),
                                    charset,
                                    "replace"))

            return u"\n".join(body).strip()

        else:   # if it is not multipart, the payload will be a string
                # representing the message body
            body = unicode(self.get_payload(decode=True),
                           get_charset(self),
                           "replace")
            return body.strip()
1269142
function GetMessageBody($msgnum, $prefer_html = true)
	{
		if ($prefer_html)
		{
			$body = $this->GetPart($msgnum, "TEXT/HTML");
			$body = $body ? $body : $this->GetPart($msgnum, "TEXT/PLAIN");
		}
		else
		{
			$body = $this->GetPart($msgnum, "TEXT/PLAIN");
			$body = $body ? $body : $this->GetPart($msgnum, "TEXT/HTML");
		}
		
		return $body;
	}
142286
def get_body(self, msg):
        

        body = ""
        charset = ""

        if msg.is_multipart():
            for part in msg.walk():
                ctype = part.get_content_type()
                cdispo = str(part.get('Content-Disposition'))

                # skip any text/plain (txt) attachments
                if ctype == 'text/plain' and 'attachment' not in cdispo:
                    body = part.get_payload(decode=True)  # decode
                    charset = part.get_content_charset()
                    break

        # not multipart - i.e. plain text, no attachments, keeping fingers crossed
        else:
            body = msg.get_payload(decode=True)
            charset = msg.get_content_charset()

        return body.decode(charset)