c 20012006 python software foundation barry warsaw contact emailsigpython org various types of useful iterators and generators all bodylineiterator typedsubpartiterator walk do not include structure since it s part of the debugging api import sys from io import stringio this function will become a method of the message class def walkself yield self if self ismultipart for subpart in self getpayload yield from subpart walk these two functions are imported into the iterators py interface module def bodylineiteratormsg decodefalse for subpart in msg walk payload subpart getpayloaddecodedecode if isinstancepayload str yield from stringiopayload def typedsubpartiteratormsg maintype text subtypenone for subpart in msg walk if subpart getcontentmaintype maintype if subtype is none or subpart getcontentsubtype subtype yield subpart def structuremsg fpnone level0 includedefaultfalse c 2001 2006 python software foundation barry warsaw contact email sig python org various types of useful iterators and generators do not include _structure since it s part of the debugging api this function will become a method of the message class walk over the message tree yielding each subpart the walk is performed in depth first order this method is a generator these two functions are imported into the iterators py interface module iterate over the parts returning string payloads line by line optional decode default false is passed through to get_payload iterate over the subparts with a given mime type use maintype as the main mime type to match against this defaults to text optional subtype is the mime subtype to match against if omitted only the main type is matched a handy debugging aid
__all__ = [
    'body_line_iterator',
    'typed_subpart_iterator',
    'walk',
    
    ]

import sys
from io import StringIO



def walk(self):
    
    yield self
    if self.is_multipart():
        for subpart in self.get_payload():
            yield from subpart.walk()



def body_line_iterator(msg, decode=False):
    
    for subpart in msg.walk():
        payload = subpart.get_payload(decode=decode)
        if isinstance(payload, str):
            yield from StringIO(payload)


def typed_subpart_iterator(msg, maintype='text', subtype=None):
    
    for subpart in msg.walk():
        if subpart.get_content_maintype() == maintype:
            if subtype is None or subpart.get_content_subtype() == subtype:
                yield subpart


def _structure(msg, fp=None, level=0, include_default=False):
    
    if fp is None:
        fp = sys.stdout
    tab = ' ' * (level * 4)
    print(tab + msg.get_content_type(), end='', file=fp)
    if include_default:
        print(' [%s]' % msg.get_default_type(), file=fp)
    else:
        print(file=fp)
    if msg.is_multipart():
        for subpart in msg.get_payload():
            _structure(subpart, fp, level+1, include_default)