Read mail, parse it and return a Message instance.
170211
def message(self):
        
        logger.debug("Parsing mail at {} ...".format(self.path))
        with open(self.path, 'rb') as mail_file:
            if PY2:
                message = email.message_from_file(mail_file)
            else:
                message = email.message_from_binary_file(mail_file)
        return message
51926
def from_text(text):
    """"""

    # 'text' can also be a file, but we don't publish that fact
    # since it's an implementation detail.  The official file
    # interface is from_file().

    m = Message()

    reader = _TextReader(text, m)
    reader.read()

    return m
434688
def parse_text_urls(mesg):
    """"""

    rval = []

    loc = 0

    for match in URLRE.finditer(mesg):
        if loc < match.start():
            rval.append(Chunk(mesg[loc:match.start()], None))
        # Turn email addresses into mailto: links
        email = match.group("email")
        if email and "mailto" not in email:
            mailto = "mailto:{}".format(email)
        else:
            mailto = match.group(1)
        rval.append(Chunk(None, mailto))
        loc = match.end()

    if loc < len(mesg):
        rval.append(Chunk(mesg[loc:], None))

    return rval
758441
def message_from_file(fp, *args, **kws):
    
    from future.backports.email.parser import Parser
    return Parser(*args, **kws).parse(fp)
104982
def parse(cls, msg):
        """"""
        lines = msg.splitlines()
        method, uri, version = lines[0].split()
        headers = cls.parse_headers('\r\n'.join(lines[1:]))
        return cls(version=version, uri=uri, method=method, headers=headers)
109816
def parse_email(self, email_info):
        
        name, email = rfc822.parseaddr(email_info)

        # more than likely a string was passed here instead of an email address
        if "@" not in email:
            name = email
            email = None

        if not name:
            name = None

        if not email:
            email = None

        self.name = name
        self.email = email
        return name, email
382197
def get_raw_email(self):
        
        if 'email' in self.payload:
            raw_email = email.message_from_string(self.payload['email'])
            return raw_email
        else:
            return None
1322314
def _filter(msgdata, mailparser, mdfolder, mailfilters):
    """"""
    if mailfilters:
        for f in mailfilters:
            msg = mailparser.parse(StringIO(msgdata))
            rule = f(msg, folder=mdfolder)
            if rule:
                yield rule
    return
365524
def _parse(self, line):
        """"""
        try:
            result = line.split(':', maxsplit=4)
            filename, line_num_txt, column_txt, message_type, text = result
        except ValueError:
            return

        try:
            self.line_num = int(line_num_txt.strip())
            self.column = int(column_txt.strip())
        except ValueError:
            return

        self.filename = filename
        self.message_type = message_type.strip()
        self.text = text.strip()
        self.valid = True
488290
def message(self):
        
        return '\n'.join(
            [self.from_email, str(self.to), self.subject, self.body])
1284235
def from_raw_message(cls, rawmessage):
        """"""
        if (rawmessage[5] &
                MESSAGE_FLAG_EXTENDED_0X10) == MESSAGE_FLAG_EXTENDED_0X10:
            if len(rawmessage) >= ExtendedSend.receivedSize:
                msg = ExtendedSend.from_raw_message(rawmessage)
            else:
                msg = None
        else:
            msg = StandardSend(rawmessage[2:5],
                               {'cmd1': rawmessage[6],
                                'cmd2': rawmessage[7]},
                               flags=rawmessage[5],
                               acknak=rawmessage[8:9])
        return msg
1055035
def read(self):
        

        self.found_visible = False

        is_multi_quote_header = self.MULTI_QUOTE_HDR_REGEX_MULTILINE.search(self.text)
        if is_multi_quote_header:
            self.text = self.MULTI_QUOTE_HDR_REGEX.sub(is_multi_quote_header.groups()[0].replace('\n', ''), self.text)

        # Fix any outlook style replies, with the reply immediately above the signature boundary line
        #   See email_2_2.txt for an example
        self.text = re.sub('([^\n])(?=\n ?[_-]{7,})', '\\1\n', self.text, re.MULTILINE)

        self.lines = self.text.split('\n')
        self.lines.reverse()

        for line in self.lines:
            self._scan_line(line)

        self._finish_fragment()

        self.fragments.reverse()

        return self
305150
def message_me(msg)
			@msg = msg
			mail from: @msg.email, subject: @msg.subject, body: @msg.content
		end
907242
def read_message_from_pipe(pipe_handle):
    
    data = yield From(read_message_bytes_from_pipe(pipe_handle))
    assert isinstance(data, bytes)
    raise Return(data.decode('utf-8', 'ignore'))
852013
def _read_message(self):
        
        # first 4 bytes is Big-Endian payload length
        payload_info = self._read_bytes_from_socket(4)
        read_len = unpack(">I", payload_info)[0]

        # now read the payload
        payload = self._read_bytes_from_socket(read_len)

        # pylint: disable=no-member
        message = cast_channel_pb2.CastMessage()
        message.ParseFromString(payload)

        return message
865066
def from_protobuf(cls, msg):
        """"""
        if not isinstance(msg, cls._protobuf_cls):
            raise TypeError("Expected message of type "
                            "%r" % cls._protobuf_cls.__name__)
        kwargs = {k: getattr(msg, k) for k in cls._get_params()}
        return cls(**kwargs)
555977
def _parseMessage(self, content):
        """"""
        self._seq = content.get("seq", "0")

        if "lb_info" in content:
            self._sticky = content["lb_info"]["sticky"]
            self._pool = content["lb_info"]["pool"]

        if "batches" in content:
            for batch in content["batches"]:
                self._parseMessage(batch)

        if "ms" not in content:
            return

        for m in content["ms"]:
            mtype = m.get("type")
            try:
                # Things that directly change chat
                if mtype == "delta":
                    self._parseDelta(m)
                # Inbox
                elif mtype == "inbox":
                    self.onInbox(
                        unseen=m["unseen"],
                        unread=m["unread"],
                        recent_unread=m["recent_unread"],
                        msg=m,
                    )

                # Typing
                elif mtype == "typ" or mtype == "ttyp":
                    author_id = str(m.get("from"))
                    thread_id = m.get("thread_fbid")
                    if thread_id:
                        thread_type = ThreadType.GROUP
                        thread_id = str(thread_id)
                    else:
                        thread_type = ThreadType.USER
                        if author_id == self._uid:
                            thread_id = m.get("to")
                        else:
                            thread_id = author_id
                    typing_status = TypingStatus(m.get("st"))
                    self.onTyping(
                        author_id=author_id,
                        status=typing_status,
                        thread_id=thread_id,
                        thread_type=thread_type,
                        msg=m,
                    )

                # Delivered

                # Seen
                # elif mtype == "m_read_receipt":
                #
                #     self.onSeen(m.get('realtime_viewer_fbid'), m.get('reader'), m.get('time'))

                elif mtype in ["jewel_requests_add"]:
                    from_id = m["from"]
                    self.onFriendRequest(from_id=from_id, msg=m)

                # Happens on every login
                elif mtype == "qprimer":
                    self.onQprimer(ts=m.get("made"), msg=m)

                # Is sent before any other message
                elif mtype == "deltaflow":
                    pass

                # Chat timestamp
                elif mtype == "chatproxy-presence":
                    statuses = dict()
                    for id_, data in m.get("buddyList", {}).items():
                        statuses[id_] = ActiveStatus._from_chatproxy_presence(id_, data)
                        self._buddylist[id_] = statuses[id_]

                    self.onChatTimestamp(buddylist=statuses, msg=m)

                # Buddylist overlay
                elif mtype == "buddylist_overlay":
                    statuses = dict()
                    for id_, data in m.get("overlay", {}).items():
                        old_in_game = None
                        if id_ in self._buddylist:
                            old_in_game = self._buddylist[id_].in_game

                        statuses[id_] = ActiveStatus._from_buddylist_overlay(
                            data, old_in_game
                        )
                        self._buddylist[id_] = statuses[id_]

                    self.onBuddylistOverlay(statuses=statuses, msg=m)

                # Unknown message type
                else:
                    self.onUnknownMesssageType(msg=m)

            except Exception as e:
                self.onMessageError(exception=e, msg=m)