mailshow1.py

来自「python web programming 部分」· Python 代码 · 共 60 行

PY
60
字号
import mailhandler
import multifile, mimetools, sys

MFILE = "mailbox.txt"


class mailStream:

    def __init__(self, filename):
        try:
            self.fp = open(filename, "r")
            print "+++Opened", filename
        except IOError:
            sys.exit("Could not open mailfile '%s'" % filename)
        self.mb = mailhandler.MimeMailbox(self.fp)

    def next(self):
        ptr = self.fp.tell()        # save start point
        msg = self.msg = self.mb.next()   # read next from mailbox
        atts = self.atts = []
        if msg:
            boundary = msg.getparam("boundary")
            if boundary:
                mf = multifile.MultiFile(self.fp)
                                    # create Multifile
                mf.push(boundary)   # save for recognition
                self.fp.seek(ptr)   # point to multifile start
                while mf.next():    # each message
                    atts.append(mimetools.Message(mf))
                                    # read up to next boundary
                mf.pop()            # restore previous
            return msg, atts        # return message and attachments
        else:
            return None, None       # no message

    def __getattr__(self, attrname):
        "Delegate unrecognised methods/attributes to the Message object."
        return getattr(self.msg, attrname)

m = 0
ms = mailStream(MFILE)      # create the message stream

while 1:                    # forever
    msg, atts = ms.next()   # get next message
    if msg is None:         # quit if there's nothing
        break
    m += 1                  # bump count
    if atts:
        a = 0
        print "Mail %d: multipart with %d attachments" % (m, len(atts))
        for att in atts:
            a += 1
            print "Att", a, "Type: ", att.gettype(), \
                    "encoding:", att.getencoding(),
            print "File:", att.getparam("name")
    else:
        print "Mail %d: plain message" % m, "from", msg['from']
    print "---------------------------------------------"

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?