zoukankan      html  css  js  c++  java
  • python 利用imap接收邮件,并保存附件

    def SaveAttachImap():# login the imap server ,retrive the  new mails ,and download the attachments.

        M = imaplib.IMAP4(mail_host,mail_port)
        #print M


        M.login(mail_user,mail_pass)

        M.select('INBOX',False)
        #result, message = M.select('INBOX',False)
        typ, data = M.search(None, 'UNSEEN')
        print data
        for num in string.split(data[0]):
            try:
                typ, data = M.fetch(num, '(RFC822)')
                #print data
                msg = email.message_from_string(data[0][1])
                for par in msg.walk():
                #if not par.is_multipart():
                    name = par.get_filename()
                    print 'name',name

                    #name2 = par.get_filename()
                    #print 'name2',name2


                    if name:
                        dstdir =dirname+name
                        print 'dirname',dstdir
                        #print 'name',name
                        data = par.get_payload(decode=True)
                        #print dstdir
                        try:
                            f = open(dstdir, 'wb') #注意一定要用wb来打开文件,因为附件一般都是二进制文件
                            print 'save attfile %s succeed'%dstdir
                        except:
                            print 'open  file name error'
                        f.write(data)
                        f.close()

                    #print "_______________________________"
            except Exception,e:
                print 'got msg error: %s' % e

        M.close()
        M.logout()

  • 相关阅读:
    day26:面向对象进阶:set、get、del反射和内置
    day26、面向对象进阶:多态、封装、反射
    day25、 静态属性、类方法、静态方法、组合、继承、
    day24:面向对象设计与面向对象编程、类和对象
    day23:s
    day21、模块
    阿里云ECS服务器挂载磁盘
    Python爬虫总结——常见的报错、问题及解决方案
    Python爬虫实战——反爬机制的解决策略【阿里】
    Python爬虫实战——反爬策略之模拟登录【CSDN】
  • 原文地址:https://www.cnblogs.com/maseng/p/3491127.html
Copyright © 2011-2022 走看看