创建简单多分组信息
import email.mime.multipart
import email.mime.text
import pprint
# 创建多分组消息
def create():
top = email.mime.multipart.MIMEMultipart()
top['From'] = 'Art <arthur@camelot.org>'
top['To'] = 'PP4E@learning-python.com'
sub1 = email.mime.text.MIMEText('Nice red uniforms ...\n')
sub2 = email.mime.text.MIMEText(open('data').read())
sub2.add_header('Content-Disposition','attachment',filename='data')
top.attach(sub1)
top.attach(sub2)
return top
if __name__ == '__main__':
message = create()
pprint.pprint(message.as_string())
输出:
('Content-Type: multipart/mixed; '
'boundary="===============7835908221502146373=="\n'
'MIME-Version: 1.0\n'
'From: Art <arthur@camelot.org>\n'
'To: PP4E@learning-python.com\n'
'\n'
'--===============7835908221502146373==\n'
'Content-Type: text/plain; charset="us-ascii"\n'
'MIME-Version: 1.0\n'
'Content-Transfer-Encoding: 7bit\n'
'\n'
'Nice red uniforms ...\n'
'\n'
'--===============7835908221502146373==\n'
'Content-Type: text/plain; charset="us-ascii"\n'
'MIME-Version: 1.0\n'
'Content-Transfer-Encoding: 7bit\n'
'Content-Disposition: attachment; filename="data"\n'
'\n'
'Line1\n'
'Line2\n'
'Line3\n'
'--===============7835908221502146373==--\n')
解析简单多分组信息
# 解析多分组消息
import email.parser
def resolve(text):
if text:
message = email.parser.Parser().parsestr(text)
print(message['From'])
print(message['To'])
print()
for part in message.walk():
print(part.get_content_type())
print(part.get_payload())
print()
else:
print('Message text is None')
if __name__ == '__main__':
message = create()
resolve(message.as_string())
输出:
Art <arthur@camelot.org>
PP4E@learning-python.com
multipart/mixed
[<email.message.Message object at 0x000001CCA4EE1668>, <email.message.Message object at 0x000001CCA4EE1780>]
text/plain
Nice red uniforms ...
text/plain
Line1
Line2
Line3