Ejemplo n.º 1
0
def full_format_to_message_object(parts: Union[dict, list],
                                  message: MIMEBase = None) -> MIMEBase:
    if not message:
        # This is the root part
        maintype, subtype = parts["mimeType"].split("/", 1)
        message = MIMEBase(maintype, subtype)
        for header in parts["headers"]:
            message[header["name"]] = header["value"]
        if message.get_content_maintype() == "multipart":
            full_format_to_message_object(parts["parts"], message)
        else:
            message.set_payload(parts["body"].get("data"))
    else:
        for part in parts:
            if part["mimeType"].split("/")[0] == "multipart":
                message_part = MIMEMultipart("mixed")
                full_format_to_message_object(part["parts"], message_part)
                message.attach(message_part)
            else:
                try:
                    maintype, subtype = part["mimeType"].split("/", 1)
                except ValueError:
                    # There's no valid mimetype, I saw the python parser set the mimetype to text/plain
                    # when it did not understand the mimetype.
                    maintype, subtype = "text", "plain"
                message_part = MIMEBase(maintype, subtype)
                for header in part["headers"]:
                    message_part[header["name"]] = header["value"]
                # Dispite the Content-Transfer-Encoding, it seems like everything is encoded
                # in b64
                data = base64.urlsafe_b64decode(part["body"].get("data",
                                                                 "")).decode()
                message_part.set_payload(data)
                message.attach(message_part)
    return message