Python email.message.Message() Examples
The following are 30
code examples of email.message.Message().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
email.message
, or try the search function
.
Example #1
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_set_param(self): eq = self.assertEqual msg = Message() msg.set_param('charset', 'iso-2022-jp') eq(msg.get_param('charset'), 'iso-2022-jp') msg.set_param('importance', 'high value') eq(msg.get_param('importance'), 'high value') eq(msg.get_param('importance', unquote=False), '"high value"') eq(msg.get_params(), [('text/plain', ''), ('charset', 'iso-2022-jp'), ('importance', 'high value')]) eq(msg.get_params(unquote=False), [('text/plain', ''), ('charset', '"iso-2022-jp"'), ('importance', '"high value"')]) msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy') eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
Example #2
Source File: email_utils.py From app with MIT License | 6 votes |
def get_addrs_from_header(msg: Message, header) -> [str]: """Get all addresses contained in `header` Used for To or CC header. """ ret = [] header_content = msg.get_all(header) if not header_content: return ret for addrs in header_content: # force convert header to string, sometimes addrs is Header object addrs = str(addrs) for addr in addrs.split(","): ret.append(addr.strip()) # do not return empty string return [r for r in ret if r]
Example #3
Source File: email_utils.py From app with MIT License | 6 votes |
def get_spam_info(msg: Message) -> (bool, str): """parse SpamAssassin header to detect whether a message is classified as spam. Return (is spam, spam status detail) The header format is ```X-Spam-Status: No, score=-0.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,RCVD_IN_DNSWL_BLOCKED,RCVD_IN_MSPIKE_H2,SPF_PASS, URIBL_BLOCKED autolearn=unavailable autolearn_force=no version=3.4.2``` """ spamassassin_status = msg["X-Spam-Status"] if not spamassassin_status: return False, "" # yes or no spamassassin_answer = spamassassin_status[: spamassassin_status.find(",")] return spamassassin_answer.lower() == "yes", spamassassin_status
Example #4
Source File: bdist_wheel.py From jbox with MIT License | 6 votes |
def write_wheelfile(self, wheelfile_base, generator='bdist_wheel (' + wheel.__version__ + ')'): from email.message import Message msg = Message() msg['Wheel-Version'] = '1.0' # of the spec msg['Generator'] = generator msg['Root-Is-Purelib'] = str(self.root_is_pure).lower() # Doesn't work for bdist_wininst impl_tag, abi_tag, plat_tag = self.get_tag() for impl in impl_tag.split('.'): for abi in abi_tag.split('.'): for plat in plat_tag.split('.'): msg['Tag'] = '-'.join((impl, abi, plat)) wheelfile_path = os.path.join(wheelfile_base, 'WHEEL') logger.info('creating %s', wheelfile_path) with open(wheelfile_path, 'w') as f: Generator(f, maxheaderlen=0).flatten(msg)
Example #5
Source File: azure_bdist_wheel.py From botbuilder-python with MIT License | 6 votes |
def write_wheelfile( self, wheelfile_base, generator="bdist_wheel (" + wheel_version + ")" ): from email.message import Message msg = Message() msg["Wheel-Version"] = "1.0" # of the spec msg["Generator"] = generator msg["Root-Is-Purelib"] = str(self.root_is_pure).lower() # Doesn't work for bdist_wininst impl_tag, abi_tag, plat_tag = self.get_tag() for impl in impl_tag.split("."): for abi in abi_tag.split("."): for plat in plat_tag.split("."): msg["Tag"] = "-".join((impl, abi, plat)) wheelfile_path = os.path.join(wheelfile_base, "WHEEL") logger.info("creating %s", wheelfile_path) with open(wheelfile_path, "w") as f: Generator(f, maxheaderlen=0).flatten(msg)
Example #6
Source File: message.py From BinderFilter with MIT License | 6 votes |
def __init__(self, _msg, _subtype='rfc822'): """Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). """ MIMENonMultipart.__init__(self, 'message', _subtype) if not isinstance(_msg, message.Message): raise TypeError('Argument is not an instance of Message') # It's convenient to use this base class method. We need to do it # this way or we'll get an exception message.Message.attach(self, _msg) # And be sure our default type is set correctly self.set_default_type('message/rfc822')
Example #7
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_replace_header(self): eq = self.assertEqual msg = Message() msg.add_header('First', 'One') msg.add_header('Second', 'Two') msg.add_header('Third', 'Three') eq(msg.keys(), ['First', 'Second', 'Third']) eq(msg.values(), ['One', 'Two', 'Three']) msg.replace_header('Second', 'Twenty') eq(msg.keys(), ['First', 'Second', 'Third']) eq(msg.values(), ['One', 'Twenty', 'Three']) msg.add_header('First', 'Eleven') msg.replace_header('First', 'One Hundred') eq(msg.keys(), ['First', 'Second', 'Third', 'First']) eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven']) self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing')
Example #8
Source File: email_utils.py From app with MIT License | 6 votes |
def add_dkim_signature(msg: Message, email_domain: str): delete_header(msg, "DKIM-Signature") # Specify headers in "byte" form # Generate message signature sig = dkim.sign( msg.as_bytes(), DKIM_SELECTOR, email_domain.encode(), DKIM_PRIVATE_KEY.encode(), include_headers=DKIM_HEADERS, ) sig = sig.decode() # remove linebreaks from sig sig = sig.replace("\n", " ").replace("\r", "") msg["DKIM-Signature"] = sig[len("DKIM-Signature: ") :]
Example #9
Source File: test_email_renamed.py From BinderFilter with MIT License | 6 votes |
def test_getset_charset(self): eq = self.assertEqual msg = Message() eq(msg.get_charset(), None) charset = Charset('iso-8859-1') msg.set_charset(charset) eq(msg['mime-version'], '1.0') eq(msg.get_content_type(), 'text/plain') eq(msg['content-type'], 'text/plain; charset="iso-8859-1"') eq(msg.get_param('charset'), 'iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') eq(msg.get_charset().input_charset, 'iso-8859-1') # Remove the charset msg.set_charset(None) eq(msg.get_charset(), None) eq(msg['content-type'], 'text/plain') # Try adding a charset when there's already MIME headers present msg = Message() msg['MIME-Version'] = '2.0' msg['Content-Type'] = 'text/x-weird' msg['Content-Transfer-Encoding'] = 'quinted-puntable' msg.set_charset(charset) eq(msg['mime-version'], '2.0') eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"') eq(msg['content-transfer-encoding'], 'quinted-puntable')
Example #10
Source File: email_handler.py From app with MIT License | 6 votes |
def replace_str_in_msg(msg: Message, fr: str, to: str): if msg.get_content_maintype() != "text": return msg new_body = msg.get_payload(decode=True).replace(fr.encode(), to.encode()) # If utf-8 decoding fails, do not touch message part try: new_body = new_body.decode("utf-8") except: return msg cte = ( msg["Content-Transfer-Encoding"].lower() if msg["Content-Transfer-Encoding"] else None ) subtype = msg.get_content_subtype() delete_header(msg, "Content-Transfer-Encoding") delete_header(msg, "Content-Type") email.contentmanager.set_text_content(msg, new_body, subtype=subtype, cte=cte) return msg
Example #11
Source File: bdist_wheel.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def write_wheelfile(self, wheelfile_base, generator='bdist_wheel (' + wheel.__version__ + ')'): from email.message import Message msg = Message() msg['Wheel-Version'] = '1.0' # of the spec msg['Generator'] = generator msg['Root-Is-Purelib'] = str(self.root_is_pure).lower() # Doesn't work for bdist_wininst impl_tag, abi_tag, plat_tag = self.get_tag() for impl in impl_tag.split('.'): for abi in abi_tag.split('.'): for plat in plat_tag.split('.'): msg['Tag'] = '-'.join((impl, abi, plat)) wheelfile_path = os.path.join(wheelfile_base, 'WHEEL') logger.info('creating %s', wheelfile_path) with open(wheelfile_path, 'w') as f: Generator(f, maxheaderlen=0).flatten(msg)
Example #12
Source File: bdist_wheel.py From auto-alt-text-lambda-api with MIT License | 6 votes |
def write_wheelfile(self, wheelfile_base, generator='bdist_wheel (' + wheel_version + ')'): from email.message import Message msg = Message() msg['Wheel-Version'] = '1.0' # of the spec msg['Generator'] = generator msg['Root-Is-Purelib'] = str(self.root_is_pure).lower() # Doesn't work for bdist_wininst impl_tag, abi_tag, plat_tag = self.get_tag() for impl in impl_tag.split('.'): for abi in abi_tag.split('.'): for plat in plat_tag.split('.'): msg['Tag'] = '-'.join((impl, abi, plat)) wheelfile_path = os.path.join(wheelfile_base, 'WHEEL') logger.info('creating %s', wheelfile_path) with open(wheelfile_path, 'w') as f: Generator(f, maxheaderlen=0).flatten(msg)
Example #13
Source File: message.py From meddle with MIT License | 6 votes |
def __init__(self, _msg, _subtype='rfc822'): """Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). """ MIMENonMultipart.__init__(self, 'message', _subtype) if not isinstance(_msg, message.Message): raise TypeError('Argument is not an instance of Message') # It's convenient to use this base class method. We need to do it # this way or we'll get an exception message.Message.attach(self, _msg) # And be sure our default type is set correctly self.set_default_type('message/rfc822')
Example #14
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_whitespace_continuation_last_header(self): eq = self.assertEqual # Like the previous test, but the subject line is the last # header. msg = email.message_from_string("""\ From: aperson@dom.ain To: bperson@dom.ain Date: Mon, 8 Apr 2002 15:09:19 -0400 Message-ID: spam Subject: the next line has a space on it \x20 Here's the message body """) eq(msg['subject'], 'the next line has a space on it\n ') eq(msg['message-id'], 'spam') eq(msg.get_payload(), "Here's the message body\n")
Example #15
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_whitespace_continuation(self): eq = self.assertEqual # This message contains a line after the Subject: header that has only # whitespace, but it is not empty! msg = email.message_from_string("""\ From: aperson@dom.ain To: bperson@dom.ain Subject: the next line has a space on it \x20 Date: Mon, 8 Apr 2002 15:09:19 -0400 Message-ID: spam Here's the message body """) eq(msg['subject'], 'the next line has a space on it\n ') eq(msg['message-id'], 'spam') eq(msg.get_payload(), "Here's the message body\n")
Example #16
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_get_body_encoding_with_uppercase_charset(self): eq = self.assertEqual msg = Message() msg['Content-Type'] = 'text/plain; charset=UTF-8' eq(msg['content-type'], 'text/plain; charset=UTF-8') charsets = msg.get_charsets() eq(len(charsets), 1) eq(charsets[0], 'utf-8') charset = Charset(charsets[0]) eq(charset.get_body_encoding(), 'base64') msg.set_payload('hello world', charset=charset) eq(msg.get_payload(), 'aGVsbG8gd29ybGQ=\n') eq(msg.get_payload(decode=True), 'hello world') eq(msg['content-transfer-encoding'], 'base64') # Try another one msg = Message() msg['Content-Type'] = 'text/plain; charset="US-ASCII"' charsets = msg.get_charsets() eq(len(charsets), 1) eq(charsets[0], 'us-ascii') charset = Charset(charsets[0]) eq(charset.get_body_encoding(), encoders.encode_7or8bit) msg.set_payload('hello world', charset=charset) eq(msg.get_payload(), 'hello world') eq(msg['content-transfer-encoding'], '7bit')
Example #17
Source File: message.py From ironpython2 with Apache License 2.0 | 6 votes |
def __init__(self, _msg, _subtype='rfc822'): """Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). """ MIMENonMultipart.__init__(self, 'message', _subtype) if not isinstance(_msg, message.Message): raise TypeError('Argument is not an instance of Message') # It's convenient to use this base class method. We need to do it # this way or we'll get an exception message.Message.attach(self, _msg) # And be sure our default type is set correctly self.set_default_type('message/rfc822')
Example #18
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_message_from_file_with_class(self): # Create a subclass class MyMessage(Message): pass fp = openfile('msg_01.txt') try: msg = email.message_from_file(fp, MyMessage) finally: fp.close() self.assertIsInstance(msg, MyMessage) # Try something more complicated fp = openfile('msg_02.txt') try: msg = email.message_from_file(fp, MyMessage) finally: fp.close() for subpart in msg.walk(): self.assertIsInstance(subpart, MyMessage)
Example #19
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_getset_charset(self): eq = self.assertEqual msg = Message() eq(msg.get_charset(), None) charset = Charset('iso-8859-1') msg.set_charset(charset) eq(msg['mime-version'], '1.0') eq(msg.get_content_type(), 'text/plain') eq(msg['content-type'], 'text/plain; charset="iso-8859-1"') eq(msg.get_param('charset'), 'iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') eq(msg.get_charset().input_charset, 'iso-8859-1') # Remove the charset msg.set_charset(None) eq(msg.get_charset(), None) eq(msg['content-type'], 'text/plain') # Try adding a charset when there's already MIME headers present msg = Message() msg['MIME-Version'] = '2.0' msg['Content-Type'] = 'text/x-weird' msg['Content-Transfer-Encoding'] = 'quinted-puntable' msg.set_charset(charset) eq(msg['mime-version'], '2.0') eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"') eq(msg['content-transfer-encoding'], 'quinted-puntable')
Example #20
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_message_from_string_with_class(self): fp = openfile('msg_01.txt') try: text = fp.read() finally: fp.close() # Create a subclass class MyMessage(Message): pass msg = email.message_from_string(text, MyMessage) self.assertIsInstance(msg, MyMessage) # Try something more complicated fp = openfile('msg_02.txt') try: text = fp.read() finally: fp.close() msg = email.message_from_string(text, MyMessage) for subpart in msg.walk(): self.assertIsInstance(subpart, MyMessage)
Example #21
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_long_lines_with_different_header(self): eq = self.ndiffAssertEqual h = """\ List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>, <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>""" msg = Message() msg['List'] = h msg['List'] = Header(h, header_name='List') self.ndiffAssertEqual(msg.as_string(), """\ List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>, <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe> List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>, <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe> """) # Test mangling of "From " lines in the body of a message
Example #22
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_parser(self): eq = self.assertEqual msg, text = self._msgobj('msg_06.txt') # Check some of the outer headers eq(msg.get_content_type(), 'message/rfc822') # Make sure the payload is a list of exactly one sub-Message, and that # that submessage has a type of text/plain payload = msg.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) msg1 = payload[0] self.assertIsInstance(msg1, Message) eq(msg1.get_content_type(), 'text/plain') self.assertIsInstance(msg1.get_payload(), str) eq(msg1.get_payload(), '\n') # Test various other bits of the package's functionality
Example #23
Source File: message.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def message(self): encoding = self.encoding or settings.DEFAULT_CHARSET msg = SafeMIMEText(self.body, self.content_subtype, encoding) msg = self._create_message(msg) msg['Subject'] = self.subject msg['From'] = self.extra_headers.get('From', self.from_email) msg['To'] = self.extra_headers.get('To', ', '.join(self.to)) if self.cc: msg['Cc'] = ', '.join(self.cc) if self.reply_to: msg['Reply-To'] = self.extra_headers.get('Reply-To', ', '.join(self.reply_to)) # Email header names are case-insensitive (RFC 2045), so we have to # accommodate that when doing comparisons. header_names = [key.lower() for key in self.extra_headers] if 'date' not in header_names: msg['Date'] = formatdate() if 'message-id' not in header_names: # Use cached DNS_NAME for performance msg['Message-ID'] = make_msgid(domain=DNS_NAME) for name, value in self.extra_headers.items(): if name.lower() in ('from', 'to'): # From and To are already handled continue msg[name] = value return msg
Example #24
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_generate(self): # First craft the message to be encapsulated m = Message() m['Subject'] = 'An enclosed message' m.set_payload('Here is the body of the message.\n') r = MIMEMessage(m) r['Subject'] = 'The enclosing message' s = StringIO() g = Generator(s) g.flatten(r) self.assertEqual(s.getvalue(), """\ Content-Type: message/rfc822 MIME-Version: 1.0 Subject: The enclosing message Subject: An enclosed message Here is the body of the message. """)
Example #25
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_string_headerinst_eq(self): h = '<15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner\'s message of "Thu, 6 Mar 2003 13:58:21 +0100")' msg = Message() msg['Received'] = Header(h, header_name='Received-1', continuation_ws='\t') msg['Received'] = h self.ndiffAssertEqual(msg.as_string(), """\ Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> \t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100") Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100") """)
Example #26
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_valid_argument(self): eq = self.assertEqual subject = 'A sub-message' m = Message() m['Subject'] = subject r = MIMEMessage(m) eq(r.get_content_type(), 'message/rfc822') payload = r.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) subpart = payload[0] self.assertIs(subpart, m) eq(subpart['subject'], subject)
Example #27
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_long_8bit_header_no_charset(self): eq = self.ndiffAssertEqual msg = Message() msg['Reply-To'] = 'Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>' eq(msg.as_string(), """\ Reply-To: Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com> """)
Example #28
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_bad_multipart(self): eq = self.assertEqual msg1 = Message() msg1['Subject'] = 'subpart 1' msg2 = Message() msg2['Subject'] = 'subpart 2' r = MIMEMessage(msg1) self.assertRaises(errors.MultipartConversionError, r.attach, msg2)
Example #29
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_get_content_maintype_error(self): msg = Message() msg['Content-Type'] = 'no-slash-in-this-string' self.assertEqual(msg.get_content_maintype(), 'text')
Example #30
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_long_8bit_header(self): eq = self.ndiffAssertEqual msg = Message() h = Header('Britische Regierung gibt', 'iso-8859-1', header_name='Subject') h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte') msg['Subject'] = h eq(msg.as_string(), """\ Subject: =?iso-8859-1?q?Britische_Regierung_gibt?= =?iso-8859-1?q?gr=FCnes?= =?iso-8859-1?q?_Licht_f=FCr_Offshore-Windkraftprojekte?= """)