Python笔记 之 email模块(简单例子)

创建简单多分组信息

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值