blob: 29a9933b676f7ae0becfe8d432d316fc5ee46d91 [file] [log] [blame]
Guido van Rossuma8763e51996-08-26 18:33:32 +00001"""Generic MIME writer.
2
3Classes:
4
5MimeWriter - the only thing here.
6
7"""
8
Guido van Rossuma8763e51996-08-26 18:33:32 +00009
10import string
11import mimetools
12
13
14class MimeWriter:
15
16 """Generic MIME writer.
17
18 Methods:
19
20 __init__()
21 addheader()
22 flushheaders()
23 startbody()
24 startmultipartbody()
25 nextpart()
26 lastpart()
27
28 A MIME writer is much more primitive than a MIME parser. It
29 doesn't seek around on the output file, and it doesn't use large
30 amounts of buffer space, so you have to write the parts in the
31 order they should occur on the output file. It does buffer the
32 headers you add, allowing you to rearrange their order.
33
34 General usage is:
35
36 f = <open the output file>
37 w = MimeWriter(f)
38 ...call w.addheader(key, value) 0 or more times...
39
40 followed by either:
41
42 f = w.startbody(content_type)
43 ...call f.write(data) for body data...
44
45 or:
46
47 w.startmultipartbody(subtype)
48 for each part:
49 subwriter = w.nextpart()
50 ...use the subwriter's methods to create the subpart...
51 w.lastpart()
52
53 The subwriter is another MimeWriter instance, and should be
54 treated in the same way as the toplevel MimeWriter. This way,
55 writing recursive body parts is easy.
56
57 Warning: don't forget to call lastpart()!
58
59 XXX There should be more state so calls made in the wrong order
60 are detected.
61
62 Some special cases:
63
64 - startbody() just returns the file passed to the constructor;
65 but don't use this knowledge, as it may be changed.
66
67 - startmultipartbody() actually returns a file as well;
68 this can be used to write the initial 'if you can read this your
69 mailer is not MIME-aware' message.
70
71 - If you call flushheaders(), the headers accumulated so far are
72 written out (and forgotten); this is useful if you don't need a
73 body part at all, e.g. for a subpart of type message/rfc822
74 that's (mis)used to store some header-like information.
75
76 - Passing a keyword argument 'prefix=<flag>' to addheader(),
77 start*body() affects where the header is inserted; 0 means
78 append at the end, 1 means insert at the start; default is
79 append for addheader(), but insert for start*body(), which use
80 it to determine where the Content-Type header goes.
81
82 """
83
84 def __init__(self, fp):
85 self._fp = fp
86 self._headers = []
87
88 def addheader(self, key, value, prefix=0):
89 lines = string.splitfields(value, "\n")
90 while lines and not lines[-1]: del lines[-1]
91 while lines and not lines[0]: del lines[0]
92 for i in range(1, len(lines)):
93 lines[i] = " " + string.strip(lines[i])
94 value = string.joinfields(lines, "\n") + "\n"
95 line = key + ": " + value
96 if prefix:
97 self._headers.insert(0, line)
98 else:
99 self._headers.append(line)
100
101 def flushheaders(self):
102 self._fp.writelines(self._headers)
103 self._headers = []
104
105 def startbody(self, ctype, plist=[], prefix=1):
106 for name, value in plist:
107 ctype = ctype + ';\n %s=\"%s\"' % (name, value)
108 self.addheader("Content-Type", ctype, prefix=prefix)
109 self.flushheaders()
110 self._fp.write("\n")
111 return self._fp
112
113 def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
114 self._boundary = boundary or mimetools.choose_boundary()
115 return self.startbody("multipart/" + subtype,
116 [("boundary", self._boundary)] + plist,
117 prefix=prefix)
118
119 def nextpart(self):
120 self._fp.write("\n--" + self._boundary + "\n")
121 return self.__class__(self._fp)
122
123 def lastpart(self):
124 self._fp.write("\n--" + self._boundary + "--\n")
125
126
127if __name__ == '__main__':
128 print "To test the MimeWriter module, run TestMimeWriter.py."