【问题描述】使用Python如何批量下载邮箱附件呢?
比如下载下图箭头所指三封邮件的附件:
【小千解答】使用imapclient库,示例代码如下:
import imapclient import datetime as dt from email.parser import BytesParser from email.policy import default # from email.header import Header,decode_header with imapclient.IMAPClient('imap.163.com') as xqmail: xqmail.login('shaoqian9527@163.com','xqoffice.cn') xqmail.id_({'name':'IMAPClient','version':'2.2.0'}) xqmail.select_folder('INBOX',True) mids = xqmail.search([u'SINCE',dt.date(2021,6,3)]) for mid in mids: mail = xqmail.fetch(mid,['BODY[]']) raw_msg = mail[mid][b'BODY[]'] msg = BytesParser(policy=default).parsebytes(raw_msg) x = 0 attname = '' for part in msg.walk(): if not part.is_multipart(): xqfile = part.get_filename() if xqfile: x += 1 # h = Header(xqfile) # dh = decode_header(h)[0] # xqfile = dh[0] # if dh[1]: # xqfile = dh[0].decode(dh[1]) # 下载附件 attdata = part.get_payload(decode=True) with open('d:/xqoffice/' + xqfile,'wb') as f: f.write(attdata) attname += ('\n' + str(x) + '.' + xqfile) if x: rq = dt.datetime.strptime(msg['Date'],'%a, %d %b %Y %H:%M:%S +0800') strrq = dt.datetime.strftime(rq,'%Y-%m-%d') print('日期:' + strrq) print('主题:' + msg['Subject']) print('附件:',end='') print(attname,'\n')
运行结果:
【参考资料】