使用python编程实现IMAP协议下载发件箱的邮件

imap4命令的详细说明可参考:http://james.apache.org/server/rfclist/imap4/rfc2060.txt
imap4有个list命令可以查看邮箱中的所有文件夹,如收件箱,发件箱,草稿箱等,python代码如下:

imapclient = imaplib.IMAP4_SSL(imap_server,"993")
imapclient.login(email_user,password)
print(imapclient.list())

对于163邮箱,输出如下: “INBOX”表示收件箱,”&g0l6P3ux-“表示收件箱,”&XfJT0ZAB-“表示发件箱

('OK', [b'() "/" "INBOX"', b'(\\Drafts) "/" "&g0l6P3ux-"', b'(\\Sent) "/" "&XfJT0ZAB-"', b'(\\Trash) "/" "&XfJSIJZk-"', b'(\\Junk) "/" "&V4NXPpCuTvY-"', b'() "/" "&dcVr0mWHTvZZOQ-"'])

对于yahoo邮箱,输出如下:

('OK', [b'(\\Archive \\HasNoChildren) "/" "Archive"', b'(\\Junk \\HasNoChildren) "/" "Bulk Mail"', b'(\\Drafts \\HasNoChildren) "/" "Draft"', b'(\\HasNoChildren) "/" "Inbox"', b'(\\Sent \\HasNoChildren) "/" "Sent"', b'(\\Trash \\HasNoChildren) "/" "Trash"'])

然后选择发件箱

response,data=imapclient.select('Sent',False)#针对yahoo邮箱
response,data=imapclient.select('&XfJT0ZAB-',False)#针对163邮箱
typ, data = imapclient.search(None, 'ALL')
mail_number = data[0].split()
for num in mail_number:
	typ, data = imapclient.fetch(num, '(UID BODY.PEEK[])')
	if 'OK'!=typ:
		print('fetch mail failed!',num)
		continue
	#开始处理邮件,可以写到文件中
	filename = './file/imap/'+mail_box+'/'+email_user+'_imap_'+num.decode()+".eml"
	emlfile = open(filename,'wb')
	emlfile.write(data[0][1])
	emlfile.close()

同理,可以用上述方法下载草稿箱、垃圾箱的邮件

    原文作者:antivice
    原文地址: https://blog.csdn.net/zfs2008zfs/article/details/89026032
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞