使用Python (3.2.2) 的poplib收取GMAIL的邮件

#!/usr/bin/python
import poplib
import email
import string

mailServer=poplib.POP3_SSL('pop.gmail.com')
mailServer.user('flowf@gmail.com')
mailServer.pass_('******')
(mailCount,size)=mailServer.stat()

print('Mails: {0}'.format(mailCount))


for i in range(1, mailCount+1):
    print('第{0}封邮件'.format(i))
    (hdr,messages,octet)=mailServer.retr(i)
    #messages = [message.decode('utf-8') for message in messages]
    mail=email.message_from_bytes('\n'.encode('utf-8').join(messages))
    subject = email.header.decode_header(mail.get('subject'))
    if type(subject[0][0]) in (type(b' '),):
        print("邮件标题:" + subject[0][0].decode(subject[0][1]))
    else:
        print("邮件标题:" + subject[0][0])
    
    for par in mail.walk():
        if not par.is_multipart():
            #附件
            name = par.get_param('name')
            if name:
                dh = email.header.decode_header(name)
                if type(dh[0][0]) in (type(b' '), ):
                    if dh[0][1] == None:
                        fname = dh[0][0].decode()
                    else:
                        fname = dh[0][0].decode(dh[0][1])
                else:
                    fname = dh[0][0]
                print('附件名:' + fname)
                data = par.get_payload(decode=True)

                try:
                    f = open(fname, 'wb')
                except:
                    print('附件名有非法字符')
                f.write(data)
                f.close()
            else:
                #邮件内容
                ch = par.get_content_charset()
                if ch == None:
                    print(par.get_payload(decode=True).decode())
                else:
                    print(par.get_payload(decode=True).decode(ch))
                    
    print("=================================")

    #mailServer.dele(i)
    
#mailServer.quit()

转载于:https://my.oschina.net/flowf/blog/55625

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值