本文整理汇总了Python中email.message.Message方法的典型用法代码示例。如果您正苦于以下问题:Python message.Message方法的具体用法?Python message.Message怎么用?Python message.Message使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类email.message
的用法示例。
在下文中一共展示了message.Message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_wheelfile
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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)
示例2: replace_str_in_msg
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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
示例3: add_dkim_signature
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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: ") :]
示例4: get_addrs_from_header
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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]
示例5: get_spam_info
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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
示例6: write_wheelfile
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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)
示例7: message
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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
示例8: __init__
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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')
示例9: test_getset_charset
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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')
示例10: test_set_param
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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')
示例11: test_replace_header
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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')
示例12: test_long_lines_with_different_header
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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
示例13: test_generate
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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.
""")
示例14: test_parser
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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
示例15: test_message_from_string_with_class
# 需要导入模块: from email import message [as 别名]
# 或者: from email.message import Message [as 别名]
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)