MimeWriter.py 3.69 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
"""Generic MIME writer.

Classes:

MimeWriter - the only thing here.

"""


import mimetools

12
__all__ = ["MimeWriter"]
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

class MimeWriter:

    """Generic MIME writer.

    Methods:

    __init__()
    addheader()
    flushheaders()
    startbody()
    startmultipartbody()
    nextpart()
    lastpart()

    A MIME writer is much more primitive than a MIME parser.  It
    doesn't seek around on the output file, and it doesn't use large
    amounts of buffer space, so you have to write the parts in the
    order they should occur on the output file.  It does buffer the
    headers you add, allowing you to rearrange their order.
Tim Peters's avatar
Tim Peters committed
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    General usage is:

    f = <open the output file>
    w = MimeWriter(f)
    ...call w.addheader(key, value) 0 or more times...

    followed by either:

    f = w.startbody(content_type)
    ...call f.write(data) for body data...

    or:

    w.startmultipartbody(subtype)
    for each part:
        subwriter = w.nextpart()
50
        ...use the subwriter's methods to create the subpart...
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    w.lastpart()

    The subwriter is another MimeWriter instance, and should be
    treated in the same way as the toplevel MimeWriter.  This way,
    writing recursive body parts is easy.

    Warning: don't forget to call lastpart()!

    XXX There should be more state so calls made in the wrong order
    are detected.

    Some special cases:

    - startbody() just returns the file passed to the constructor;
      but don't use this knowledge, as it may be changed.

    - startmultipartbody() actually returns a file as well;
      this can be used to write the initial 'if you can read this your
      mailer is not MIME-aware' message.

    - If you call flushheaders(), the headers accumulated so far are
      written out (and forgotten); this is useful if you don't need a
      body part at all, e.g. for a subpart of type message/rfc822
      that's (mis)used to store some header-like information.

    - Passing a keyword argument 'prefix=<flag>' to addheader(),
      start*body() affects where the header is inserted; 0 means
      append at the end, 1 means insert at the start; default is
      append for addheader(), but insert for start*body(), which use
      it to determine where the Content-Type header goes.

    """

    def __init__(self, fp):
85 86
        self._fp = fp
        self._headers = []
87 88

    def addheader(self, key, value, prefix=0):
89
        lines = value.split("\n")
90 91 92
        while lines and not lines[-1]: del lines[-1]
        while lines and not lines[0]: del lines[0]
        for i in range(1, len(lines)):
93 94
            lines[i] = "    " + lines[i].strip()
        value = "\n".join(lines) + "\n"
95 96 97 98 99
        line = key + ": " + value
        if prefix:
            self._headers.insert(0, line)
        else:
            self._headers.append(line)
100 101

    def flushheaders(self):
102 103
        self._fp.writelines(self._headers)
        self._headers = []
104 105

    def startbody(self, ctype, plist=[], prefix=1):
106 107 108 109 110 111
        for name, value in plist:
            ctype = ctype + ';\n %s=\"%s\"' % (name, value)
        self.addheader("Content-Type", ctype, prefix=prefix)
        self.flushheaders()
        self._fp.write("\n")
        return self._fp
112 113

    def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
114 115 116 117
        self._boundary = boundary or mimetools.choose_boundary()
        return self.startbody("multipart/" + subtype,
                              [("boundary", self._boundary)] + plist,
                              prefix=prefix)
118 119

    def nextpart(self):
120 121
        self._fp.write("\n--" + self._boundary + "\n")
        return self.__class__(self._fp)
122 123

    def lastpart(self):
124
        self._fp.write("\n--" + self._boundary + "--\n")
125 126 127


if __name__ == '__main__':
128
    import test.test_MimeWriter