首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

自动收取邮件的python代码出错

2012-06-17 
自动收取邮件的python代码出错,求高手指教我想用邮件写个自动收取邮件,然后自动下到本机的python代码,但是

自动收取邮件的python代码出错,求高手指教
我想用邮件写个自动收取邮件,然后自动下到本机的python代码,但是在写入文件的时候,老是自动报错,我要把报错的地方注释掉,就不能写内容。求教高手

Python code
# -*- coding: cp936 -*-import   poplibimport   cStringIOimport   emailimport   base64import   ospop3_server = 'pop.163.com'user_name = 'XXXX@163.com'password = 'XXXX'#POP3取信M = poplib.POP3(pop3_server)M.user(user_name)M.pass_(password)#打印有多少封信numMessages = len(M.list()[1])print ('num of messages', numMessages)    for i in range(numMessages):    m = M.retr(i+1)    buf = cStringIO.StringIO()    for j in m[1]:        print >> buf, j        buf.seek(0)#解析信件内容        msg = email.message_from_file(buf)        for part in msg.walk():            contenttype = part.get_content_type()            filename = part.get_filename()            if contenttype == 'application/octet-stream':                if filename == None:                    continue                #   保存附件                f   =   open( "mail%d_%s.attach" % (i+1,filename), 'wb')                f.write(base64.decodestring(part.get_payload()))                f.close()            elif contenttype == 'text/plain':                #   保存正文                f = open( "mail%d.eml " % (i+1), 'wb')                f.write(base64.decodestring(part.get_payload()))                f.close()


出错信息是:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\任务\邮件库\getEmail.py", line 40, in <module>
  f.write(base64.decodestring(part.get_payload()))
  File "C:\Python26\lib\base64.py", line 321, in decodestring
  return binascii.a2b_base64(s)
Error: Incorrect padding

[解决办法]
f.write(base64.decodestring(part.get_payload())) =》
 
f.write(base64.b64decode(part.get_payload())) 试试?
[解决办法]
Python code
def processMsg(entire_msg):    body = ''    msg = email.message_from_string(entire_msg)    if msg.is_multipart():        for part in msg.walk():            if part.get_content_type() == 'text/plain':                body = part.get_payload()                break            else:                body = msg.get_payload(decode=True)    else:        body = msg.get_payload(decode=True)    return body 

热点排行