当前位置: 首页>>代码示例>>Python>>正文


Python email.message_from_bytes方法代码示例

本文整理汇总了Python中email.message_from_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python email.message_from_bytes方法的具体用法?Python email.message_from_bytes怎么用?Python email.message_from_bytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在email的用法示例。


在下文中一共展示了email.message_from_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle_sender_email

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def handle_sender_email(envelope: Envelope):
    filename = (
        arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml"
    )
    filepath = os.path.join(SENDER_DIR, filename)

    with open(filepath, "wb") as f:
        f.write(envelope.original_content)

    LOG.d("Write email to sender at %s", filepath)

    msg = email.message_from_bytes(envelope.original_content)
    orig = get_orig_message_from_bounce(msg)
    if orig:
        LOG.warning(
            "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath
        )

    return "250 email to sender accepted" 
开发者ID:simple-login,项目名称:app,代码行数:21,代码来源:email_handler.py

示例2: get_imap_messages

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def get_imap_messages() -> Generator[EmailMessage, None, None]:
    mbox = IMAP4_SSL(settings.EMAIL_GATEWAY_IMAP_SERVER, settings.EMAIL_GATEWAY_IMAP_PORT)
    mbox.login(settings.EMAIL_GATEWAY_LOGIN, settings.EMAIL_GATEWAY_PASSWORD)
    try:
        mbox.select(settings.EMAIL_GATEWAY_IMAP_FOLDER)
        try:
            status, num_ids_data = mbox.search(None, 'ALL')
            for message_id in num_ids_data[0].split():
                status, msg_data = mbox.fetch(message_id, '(RFC822)')
                assert isinstance(msg_data[0], tuple)
                msg_as_bytes = msg_data[0][1]
                message = email.message_from_bytes(msg_as_bytes, policy=email.policy.default)
                assert isinstance(message, EmailMessage)  # https://github.com/python/typeshed/issues/2417
                yield message
                mbox.store(message_id, '+FLAGS', '\\Deleted')
            mbox.expunge()
        finally:
            mbox.close()
    finally:
        mbox.logout() 
开发者ID:zulip,项目名称:zulip,代码行数:22,代码来源:email_mirror.py

示例3: consume

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def consume(self, event: Mapping[str, Any]) -> None:
        rcpt_to = event['rcpt_to']
        msg = email.message_from_bytes(
            base64.b64decode(event["msg_base64"]),
            policy=email.policy.default,
        )
        assert isinstance(msg, EmailMessage)  # https://github.com/python/typeshed/issues/2417
        if not is_missed_message_address(rcpt_to):
            # Missed message addresses are one-time use, so we don't need
            # to worry about emails to them resulting in message spam.
            recipient_realm = decode_stream_email_address(rcpt_to)[0].realm
            try:
                rate_limit_mirror_by_realm(recipient_realm)
            except RateLimited:
                logger.warning("MirrorWorker: Rejecting an email from: %s "
                               "to realm: %s - rate limited.",
                               msg['From'], recipient_realm.name)
                return

        mirror_email(msg, rcpt_to=rcpt_to) 
开发者ID:zulip,项目名称:zulip,代码行数:22,代码来源:queue_processors.py

示例4: parse

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def parse(self):
        try:
            if self.message_type == ParserMessageType.STRING:
                msg = email.message_from_string(self.raw_message, Message)
            elif self.message_type == ParserMessageType.BYTES:
                msg = email.message_from_bytes(self.raw_message, Message)
            elif self.message_type == ParserMessageType.BINARY_FILE:
                msg = email.message_from_binary_file(self.raw_message, Message)
            else:
                raise ValueError("Invalid message_type, could not parse message.")
        except Exception:
            raise ParseEmailException

        # Do basic post-processing of the message, checking it for defects or
        # other missing information.
        if msg.defects:
            raise DefectMessageException

        # Add headers used by LEGO
        msg.original_size = len(self.raw_message)
        msg["X-MailFrom"] = self.mail_from

        return msg 
开发者ID:webkom,项目名称:lego,代码行数:25,代码来源:parser.py

示例5: __init__

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def __init__(self, message=None):
        """Initialize a Message instance."""
        if isinstance(message, email.message.Message):
            self._become_message(copy.deepcopy(message))
            if isinstance(message, Message):
                message._explain_to(self)
        elif isinstance(message, bytes):
            self._become_message(email.message_from_bytes(message))
        elif isinstance(message, str):
            self._become_message(email.message_from_string(message))
        elif isinstance(message, io.TextIOWrapper):
            self._become_message(email.message_from_file(message))
        elif hasattr(message, "read"):
            self._become_message(email.message_from_binary_file(message))
        elif message is None:
            email.message.Message.__init__(self)
        else:
            raise TypeError('Invalid message type: %s' % type(message)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:mailbox.py

示例6: test_mangled_from_with_bad_bytes

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def test_mangled_from_with_bad_bytes(self):
        source = textwrap.dedent("""\
            Content-Type: text/plain; charset="utf-8"
            MIME-Version: 1.0
            Content-Transfer-Encoding: 8bit
            From: aaa@bbb.org

        """).encode('utf-8')
        msg = email.message_from_bytes(source + b'From R\xc3\xb6lli\n')
        b = BytesIO()
        g = BytesGenerator(b, mangle_from_=True)
        g.flatten(msg)
        self.assertEqual(b.getvalue(), source + b'>From R\xc3\xb6lli\n')


# Test the basic MIMEAudio class 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:18,代码来源:test_email.py

示例7: test_binary_body_with_encode_noop

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def test_binary_body_with_encode_noop(self):
        # Issue 16564: This does not produce an RFC valid message, since to be
        # valid it should have a CTE of binary.  But the below works in
        # Python2, and is documented as working this way.
        bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
        # Treated as a string, this will be invalid code points.
        self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
        self.assertEqual(msg.get_payload(decode=True), bytesdata)
        s = BytesIO()
        g = BytesGenerator(s)
        g.flatten(msg)
        wireform = s.getvalue()
        msg2 = email.message_from_bytes(wireform)
        self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
        self.assertEqual(msg2.get_payload(decode=True), bytesdata) 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:18,代码来源:test_email.py

示例8: test_8bit_in_quopri_body

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def test_8bit_in_quopri_body(self):
        # This is non-RFC compliant data...without 'decode' the library code
        # decodes the body using the charset from the headers, and because the
        # source byte really is utf-8 this works.  This is likely to fail
        # against real dirty data (ie: produce mojibake), but the data is
        # invalid anyway so it is as good a guess as any.  But this means that
        # this test just confirms the current behavior; that behavior is not
        # necessarily the best possible behavior.  With 'decode' it is
        # returning the raw bytes, so that test should be of correct behavior,
        # or at least produce the same result that email4 did.
        m = self.bodytest_msg.format(charset='utf-8',
                                     cte='quoted-printable',
                                     bodyline='p=C3=B6stál').encode('utf-8')
        msg = email.message_from_bytes(m)
        self.assertEqual(msg.get_payload(), 'p=C3=B6stál\n')
        self.assertEqual(msg.get_payload(decode=True),
                         'pöstál\n'.encode('utf-8')) 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:19,代码来源:test_email.py

示例9: test_invalid_8bit_in_non_8bit_cte_uses_replace

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def test_invalid_8bit_in_non_8bit_cte_uses_replace(self):
        # This is similar to the previous test, but proves that if the 8bit
        # byte is undecodeable in the specified charset, it gets replaced
        # by the unicode 'unknown' character.  Again, this may or may not
        # be the ideal behavior.  Note that if decode=False none of the
        # decoders will get involved, so this is the only test we need
        # for this behavior.
        m = self.bodytest_msg.format(charset='ascii',
                                     cte='quoted-printable',
                                     bodyline='p=C3=B6stál').encode('utf-8')
        msg = email.message_from_bytes(m)
        self.assertEqual(msg.get_payload(), 'p=C3=B6st\uFFFD\uFFFDl\n')
        self.assertEqual(msg.get_payload(decode=True),
                        'pöstál\n'.encode('utf-8'))

    # test_defect_handling:test_invalid_chars_in_base64_payload 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:18,代码来源:test_email.py

示例10: decrypt

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def decrypt(smime: bytes, key: rsa.RSAPrivateKey, serial: Optional[int] = None):
    """Decrypt an S/MIME message using the RSA Private Key given.

    The recipient can be hinted using the serial parameter, otherwise we assume single recipient = the given key.
    """
    string_content = smime.decode('utf8')
    msg: Message = email.message_from_string(string_content)
    assert msg.get_content_type() == 'application/pkcs7-mime'
    assert msg.get_filename() == 'smime.p7m'
    assert msg.get('Content-Description') == 'S/MIME Encrypted Message'

    b64payload = msg.get_payload()
    payload = b64decode(b64payload)
    decrypted_data = decrypt_smime_content(payload, key)
    decrypted_msg: Message = email.message_from_bytes(decrypted_data)

    return decrypted_msg.get_payload() 
开发者ID:cmdmnt,项目名称:commandment,代码行数:19,代码来源:smime.py

示例11: fetch_email

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def fetch_email(M, msg_id):
    """Returns the given email message as a unicode string."""
    res, data = M.fetch(msg_id, '(RFC822)')
    if res == 'OK':
        # Data here is a list with 1 element containing a tuple
        # whose 2nd element is a long string containing the email
        # The content is a bytes that must be decoded
        raw_msg_txt = data[0][1]
        # In Python3, we call message_from_bytes, but this function doesn't
        # exist in Python 2.
        try:
            msg = email.message_from_bytes(raw_msg_txt)
        except AttributeError:
            msg = email.message_from_string(raw_msg_txt)
        # At this point, we have a message containing bytes (not unicode)
        # fields that will still need to be decoded, ideally according to the
        # character set specified in the message.
        return msg
    else:
        return None 
开发者ID:sorgerlab,项目名称:indra,代码行数:22,代码来源:gmail_client.py

示例12: append_literal

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def append_literal(self, data):
        tag, mailbox_name, size = self.append_literal_command
        if data == CRLF:
            if 'UIDPLUS' in self.capabilities:
                self.send_tagged_line(tag, 'OK [APPENDUID %s %s] APPEND completed.' %
                                      (self.uidvalidity, self.server_state.max_uid(self.user_login, mailbox_name)))
            else:
                self.send_tagged_line(tag, 'OK APPEND completed.')
            self.append_literal_command = None
            return

        literal_data, rest = data[:size], data[size:]
        if len(literal_data) < size:
            self.send_tagged_line(self.append_literal_command[0],
                                  'BAD literal length : expected %s but was %s' % (size, len(literal_data)))
            self.append_literal_command = None
        elif rest and rest != CRLF:
            self.send_tagged_line(self.append_literal_command[0],
                                  'BAD literal trailing data : expected CRLF but got %s' % (rest))
        else:
            m = email.message_from_bytes(data)
            self.server_state.add_mail(self.user_login, Mail(m), mailbox_name)

            if rest:
                self.append_literal(rest) 
开发者ID:bamthomas,项目名称:aioimaplib,代码行数:27,代码来源:imapserver.py

示例13: copy

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def copy(msg: Message) -> Message:
    """return a copy of message"""
    return email.message_from_bytes(msg.as_bytes()) 
开发者ID:simple-login,项目名称:app,代码行数:5,代码来源:email_utils.py

示例14: generateTestCases

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def generateTestCases(self):
        for folder in self.args.spam_folder:
            for eml in Path(folder).glob("*.eml"):
                try:
                    msg = message_from_bytes(eml.read_bytes())
                except IOError:
                    print("! Failed to read from {}".format(eml.name))

                del msg["To"]

                yield msg 
开发者ID:TKCERT,项目名称:mail-security-tester,代码行数:13,代码来源:spam.py

示例15: prepare

# 需要导入模块: import email [as 别名]
# 或者: from email import message_from_bytes [as 别名]
def prepare(self):
        """
        Prepare the `self.message` object.
        """
        if self.prepared_message:
            self.message = message_from_bytes(self.prepared_message)
            self.prepared = True
            return

        self.text = self.text or BeautifulSoup(self.html, 'html.parser').get_text(strip=True)
        self.html = self.html or mistune.markdown(self.text)

        self.message['Sender'] = stringify_address(self.sender)
        self.message['From'] = stringify_addresses(self.authors) if self.authors else stringify_address(self.sender)
        self.message['To'] = stringify_addresses(self.receivers)
        self.message['Subject'] = self.subject
        if self.cc:
            self.message['CC'] = stringify_addresses(self.cc)
        if self.bcc:
            self.message['BCC'] = stringify_addresses(self.bcc)
        if self.reply_to:
            self.message['Reply-To'] = stringify_addresses(self.reply_to)
        if self.headers:
            for key, value in self.headers.items():
                self.message[key] = value

        body = MIMEMultipart('alternative')
        plaintext_part = MIMEText(self.text, 'plain')
        html_part = MIMEText(self.html, 'html')
        body.attach(plaintext_part)
        body.attach(html_part)
        self.message.attach(body)
        self.prepared = True 
开发者ID:SkullTech,项目名称:drymail,代码行数:35,代码来源:drymail.py


注:本文中的email.message_from_bytes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。