text.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:anki-onenote-importer 作者: tmpethick 项目源码 文件源码
def decoded(message, allowed_mimetypes=None):
        """
        If the mimetype of the message is in the `allowed_mimetypes` parameter returns
        returns its content decoded. If the message is multipart find in the attachments
        a message with mimetype in the `allowed_mimetypes` parameter and returns its
        content decoded.

        Parameters
        ----------
        message: email.message.Message
            Message to decode.
        allowed_mimetypes: iterable
            Iterable object with the mimetypes will be used the select the message to
            extract its text. Only `text/plain` and `text/html` allowed or a
            `ValueError` exception will be raised.

        Returns
        -------
        message_text: str
            Returns the plain text of the message. This method will try return the text
            encoded to `utf-8`. If it can't, returns it with its original encoding. If
            it can't find the text returns `None`.

        Raises
        ------
        TypeError
            If the parameter is not an instance of :class:`email.message.Message`.
        ValueError
            If the value in the parameter allowed_mimetypes is incorrect.
        """
        if allowed_mimetypes is None:
            allowed_mimetypes = ('text/plain', 'text/html')
        wrong_mime_types = frozenset(allowed_mimetypes).difference(['text/plain', 'text/html'])
        if wrong_mime_types:
            raise ValueError("Wrong mime types: {0}".format(list(wrong_mime_types)))
        if not isinstance(message, email.message.Message):
            raise TypeError("Expected a message object.")
        if not message.is_multipart():
            if message.get_filename():
                return None
            if message.get_content_type() in allowed_mimetypes:
                return (Text.decode_text(message), 
                    message.get('Content-Location'))
            return None
        for sub_message in message.get_payload():
            if not sub_message.is_multipart() or sub_message.get_content_type() == 'multipart/alternative':
                result = Text.decoded(sub_message)
                if result:
                    return result
        return None
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号