1 登录认证
server = 'xxx.xxx'# 两种方式均可,推荐IMAP4_SSLmail = imaplib.IMAP4(server) # 默认端口imaplib.IMAP4_PORT 143mail = imaplib.IMAP4_SSL(server) # 默认端口imaplib.IMAP4_SSL_PORT 993res = mail.login(username, password)# 登录成功: ('OK', ['Success login ok'])# 登录失败:error: command LOGIN illegal in state AUTH, only allowed in states NONAUTHmail.logout()# 退出:('BYE', ['LOGOUT received'])
2 查看邮件
# login ...# 列出目录print mail.list()[0]# OKfor each in mail.list()[1]:print each# (\HasNoChildren) "/" "INBOX" - 收件箱# (\HasNoChildren) "/" "Sent Messages" - 已发送邮件# (\HasNoChildren) "/" "Drafts" - 草稿箱# (\HasNoChildren) "/" "Deleted Messages" - 已删除邮件# (\HasNoChildren) "/" "Junk" - 垃圾邮件# ...# 选择目录mail.select('INBOX')# ('OK', ['11477']) - 11477为该目录下邮件的数目# 在该目录下按状态条件搜索mail.search(None, 'UNSEEN')# ('OK', ['11477'])
3 MailBox状态
| Condition | Meaning |
|---|---|
| MESSAGES | The number of messages in the mailbox. |
| RECENT | The number of messages with the \\Recent flag set. |
| UIDNEXT | The next unique identifier value of the mailbox. |
| UIDVALIDITY | The unique identifier validity value of the mailbox. |
| UNSEEN | The number of messages which do not have the \\Seen flag set. |
# ... select# 查看未读邮件mail.search(None, 'unseen') # or new# 查看已读邮件mail.search(None, 'seen')# 按条件搜索 不生效???mail.search(None, '(SUBJECT "test")')mail.search(None, '(UNSEEN SUBJECT "test")')# 修改邮件状态mail.store('11477', '+FLAGS', '\\seen') # 设为已读mail.store('11477', '-FLAGS', '\\seen') # 设为未读# 删除邮件mail.store('11477', '+FLAGS', '\\Deleted')mail.store('11477', '-FLAGS', '\\Deleted')# 永久删除mail.expunge() # logout时才会真的删除
4 获取邮件内容
# ... select# 获取headermail.fetch('11476', '(BODY.PEEK[HEADER])')# 获取textmail.fetch('11476', '(BODY.PEEK[TEXT])')# 获取全部(header+text)mail.fetch('11476', '(RFC822)')# 获取flagsmail.fetch('11476', '(FLAGS)')# ================================# 解析邮件import emailtyp, data = mail.fetch('11476', '(RFC822)')msg = email.message_from_string(data[0][1])print msg['from']print msg['to']print msg['subject']## subject如果包含中文需要解码text, enc = email.header.decode_header(msg['subject'])[0]subject = text.decode(enc) if enc else textprint subject## 发信人邮箱获取## 邮件正文获取if msg['sender']:email_from = msg['sender']elif re.findall(r'<.+?>', msg['from']):email_from = re.findall(r'<(.+?)>', msg['from'])[0]else:email_from = msg['from']
问题:中文目录解码问题
&替换成+,再utf-7解码
for each in mail.list()[1]:catalog = each.split(' "/" ')[-1].replace('&', '+').decode('utf-7')print(catalog)# 选择目录时按原写法即可mail.select('&UXZO1mWHTvZZOQ-/&VS5UDg-')# 也可以反向转回去catalog = '其他文件夹/售后'.decode('utf-8').encode('utf-7').replace('+', '&')mail.select(catalog)

参考
