上一篇使用了pop3模块进行邮件的下载,模块提供的功能不如本篇的imap。
本篇将稍微深入的通过imap进行邮件的登陆和下载;
1、邮件登陆信息获取:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#filename:receive_imap_email.py
import imaplib, os, ConfigParser, re
import pprint
#进行用户的登陆,主要通过config文件进行主机名,用户名和密码的获取
def user_login(verbose=False):#verbose=False为函数参数定义的一种方式,在True的情况下执行
#Read the config file
config = ConfigParser.ConfigParser()
config.read(r'D:\Python\tmp\config.txt')
#Connect to the server
hostname = config.get('server', 'hostname')
if verbose:
print 'Connecting to', hostname
m = imaplib.IMAP4(hostname)
#Login to the account
username = config.get('account', 'username')
passwd = config.get('account', 'passwd')
if verbose:
print 'Logging in as ', username
m.login(username,passwd)
print type(m)#返回instance
return m
#对收件箱进行检查,列出对应的文件夹
def list_inbox():
l_box = user_login(verbose=True)
print type(l_box)
try:
typ, data = l_box.list()#注意这种赋值方式,返回值是状态和inbox,drafts,sent,trash等;即后者的两个元素依次赋给前者
print 'Response code:', typ
print 'Response:'
pprint.pprint(data)
finally:
l_box.logout()
#user_login(verbose=True)#在True的情况下执行
list_inbox()
输出:
>>> ================================ RESTART ================================
>>>
Connecting to imap.163.com
Logging in as dxx_study
<type 'instance'>
<type 'instance'>
Response code: OK
Response:
['() "/" "INBOX"',
'(\\Drafts) "/" "&g0l6P3ux-"',
'(\\Sent) "/" "&XfJT0ZAB-"',
'(\\Trash) "/" "&XfJSIJZk-"',
'(\\Junk) "/" "&V4NXPpCuTvY-"',
'() "/" "&dcVr0mWHTvZZOQ-"',
'() "/" "&Xn9USpCuTvY-"',
'() "/" "&i6KWBZCuTvY-"',
'() "/" "test"']
从以上可以看出,编码将是这个工作中的难点,因为邮件编码采用的是base64,并且还要区分发件人的编码,目前已遇到的主要有utf-8,这个一般不处理,直接输出,其次是gb2312,再次是gbk,或者英文的直接ascii。
2、邮件解码
对于解码部分又分为,邮件标题和发件人,以及邮件正文。
下面再实例记录下处理的一些方法和技巧:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#filename:receive_imap_email.py
import imaplib, os, ConfigParser, re
import pprint, sys, email, string
#reload(sys)#设置为命令窗口cmd输出
#sys.setdefaultencoding('gbk')
def user_login(verbose=False):#verbose=False为函数参数定义的一种方式,在True的情况下执行
#Read the config file
config = ConfigParser.ConfigParser()
config.read(r'D:\Python\tmp\config.txt')
#Connect to the server
hostname = config.get('server', 'hostname')
if verbose:
print 'Connecting to', hostname
m = imaplib.IMAP4(hostname)
#Login to the account
username = config.get('account', 'username')
passwd = config.get('account', 'passwd')
if verbose:
print 'Logging in as ', username
m.login(username,passwd)
return m
def list_inbox():#罗列收件箱的子目录
l_box = user_login(verbose=True)
try:
typ, data = l_box.list()#注意这种赋值方式,返回值是状态和inbox,drafts,sent,trash等
print 'Response code:', typ
print 'Response:'
pprint.pprint(data)#Mailbox names are in modified UTF7 character set.输出会出现乱码
finally:
l_box.logout()
def status_mailbox():
stat_m = user_login(verbose=True)
try:
typ, data = stat_m.list()
for line in data:#由于字符编码问题,暂无法去匹配对应收件箱的状态,未完待续
print line
finally:
stat_m.logout()
def to_unicode(s, encoding):
if encoding:
return u