以下脚本连接上我的Gmail帐号,将收件箱中2013年1月份的新语丝邮件的附件保存在当前目录的xys文件夹中。

import imaplib
import email
import os
dir_name = 'archive'
if not os.path.exists(dir_name):
os.mkdir(dir_name)
save_path = os.path.join(os.getcwd(),dir_name)
M = imaplib.IMAP4_SSL('imap.gmail.com')
M.login('leetschau@gmail.com', 'vim72python251')
M.select() # default value is inbox
search_criteria = '(From "Shi-min Fang" UNSEEN)'
# '(From "Shi-min Fang" SINCE "01-Jan-2013" BEFORE "01-FEB-2013")'
res, search_result = M.search(None, search_criteria)
for num in search_result[0].split():
typ, data = M.fetch(num, '(RFC822)')
# print 'Message %s\n%s\n' % (num, data[0][1])
email_body = data[0][1]
mail = email.message_from_string(email_body)
sender = mail['From']
subject = mail['Subject']
print "["+mail["From"]+"]: " + mail["Subject"]
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = subject+'.txt'
att_path = os.path.join(save_path, filename)
if not os.path.isfile(att_path) :
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
M.close()
M.logout()

说明:

  1. 附件保存的名字和扩展名是写死的,有兴趣的话可以研究一下怎样获得附件本身的文件名;

  2. 这个脚本的强大之处在于它不需要任何第三方库,只用python内置的imaplib,只用是支持imap的邮箱都可以用这个方法处理邮件;

  3. 这里面最有用的是邮件搜索规则(search_criteria),格式是(key1 value1 key2 value2 ...),每个value上加引号,整个表达式是一个字符串,因此也要加引号。

key除了这里的收件人、起始/终止日期,还有ALL(全部邮件),UNSEEN(未读邮件),DELETED(已删除邮件)等,key-value对之间可以随意组合;

  1. M的select方法默认值是收件箱,可以指定其他信箱,完整格式是:IMAP4.select([mailbox[, readonly]]);

参考1:http://stackoverflow.com/questions/6225763/downloading-multiple-attachments-using-imaplib

参考2:Python 2.7.3 chapter 20.10 imaplib -> 20.10.2: IMAP4 Example

最新文章

  1. 北京培训记day3
  2. Linux 用户添加sudo 权限
  3. Android中的动画机制
  4. Spatial Transformer Networks(空间变换神经网络)
  5. web桌面程序之锁屏功能分析
  6. 优化MySchool数据库(三)
  7. yum安装指定(特定)版本(旧版本)软件包的方法
  8. eclipse 创建项目时出现appcompat_v7?
  9. linux清除swap
  10. Only the original thread that created a view hierarchy can touch its views
  11. sql Server 常用存储过程的优化
  12. 如何实现HTTPSERVER
  13. linux shell——md5sum,sha1sum,sort,uniq (转)
  14. LeetCode 81. Search in Rotated Sorted Array II(在旋转有序序列中搜索之二)
  15. 对象存取器属性:getter和setter
  16. Mac环境下实现alias重命名命令(永久生效)
  17. Linux,Ubuntu,Mint 环境下 navicat 乱码问题
  18. Hadoop启动脚本分析
  19. innobackupex: error while loading shared libraries: libssl.so.6
  20. 1.docker 数据卷的备份和恢复(非大数据量)

热门文章

  1. keycloak~账号密码认证和授权码认证
  2. 海量数据Excel报表利器——EasyExcel(一 利用反射机制导出Excel)
  3. Java | 字符串缓冲区(StringBuilder)
  4. Linux groupadd and groupmod
  5. JAVA程序系统测试感受
  6. [刘阳Java]_MySQL数据优化总结_查询备忘录
  7. Xshell、winscp连不上Linux虚拟机
  8. 【模拟】玩具谜题 luogu-1563
  9. tomcat内置jdk(tomcat集成jdk)(windows环境)
  10. macOS下将可执行文件索引位置增添到PATH中