當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。