Python接收邮件 pop3 --- 邮件(3)

"""
收取邮件就是编写一个MUA作为客户端,从MDA把邮件获取到用户的电脑或者手机上.
取邮件最常用的协议是POP协议,目前版本号是3,俗称POP3。
Python内置一个poplib模块,实现了POP3协议,可以直接用来收邮件。

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320098721191b70a2cf7b5441deb01595edd8147196000
"""

class ReceiveEmail(object):
    """
    第一步:用poplib把邮件的原始文本下载到本地;

    第二部:用email解析原始文本,还原为邮件对象。这个本文没有
    """
    @classmethod
    def get_email(self):
        import poplib

        from email.parser import Parser
        from email.header import decode_header
        from email.utils import parseaddr

        # 获取邮箱 密码 和 对应邮箱POP3 服务器
        email = "[email protected]"
        password = "xxxxxx"
        pop3_server = "pop.163.com"

        # 链接到POP3服务器
        server = poplib.POP3(pop3_server)
        # 打开调试,打印出会话内容,可选
        server.set_debuglevel(1)
        # 打印POP3服务器的欢迎文字,可选
        print(server.getwelcome().decode('utf-8'))

        # 进行身份认证
        server.user(email)
        server.pass_(password)

        # stat() 返回邮件数量和占用空间,返回两个。
        print('Messages: %s. Size: %s' % server.stat())

        # list 返回所有邮件编号,第一个是返回状态信息,第二个是列表
        resp, mails, octets = server.list()
        print("邮件列表",mails)

        # 获取最新一封邮件, 注意索引号从1开始,最后是最新的
        index = len(mails)
        resp, lines, octets = server.retr(index)

        # lines存储了邮件的原始文本的每一行,
        # 可以获得整个邮件的原始文本:
        msg_content = b'\r\n'.join(lines).decode('utf-8')
        # 解析成massage对象
        msg = Parser().parsestr(msg_content)
        print(type(msg)) # <class 'email.message.Message'>

        message = msg

        # 关闭连接
        server.quit()


        # 解析邮件正文
        # https://www.cnblogs.com/zixuan-zhang/p/3402821.html
        maintype = message.get_content_maintype()
        if maintype == 'multipart':
            for part in message.get_payload():
                if part.get_content_maintype() == 'text':
                    mail_content = part.get_payload(decode=True).strip()
        elif maintype == 'text':
            mail_content = e.get_payload(decode=True).strip()
        mail_content = mail_content.decode('gbk')
        print(mail_content)
if __name__ == "__main__":
    ReceiveEmail.get_email()

猜你喜欢

转载自blog.csdn.net/sunt2018/article/details/86625963
今日推荐