blob: e898f9ff231793672ae281c770666be8953be6ec [file] [log] [blame]
Guido van Rossumc75db0b1996-08-26 16:33:30 +00001"""Generic MIME writer.
2
Raymond Hettingeraef22fb2002-05-29 16:18:42 +00003This module defines the class MimeWriter. The MimeWriter class implements
4a basic formatter for creating MIME multi-part files. It doesn't seek around
5the output file nor does it use large amounts of buffer space. You must write
6the parts out in the order that they should occur in the final file.
7MimeWriter does buffer the headers you add, allowing you to rearrange their
8order.
Guido van Rossumc75db0b1996-08-26 16:33:30 +00009
10"""
11
Guido van Rossumc75db0b1996-08-26 16:33:30 +000012
Guido van Rossumc75db0b1996-08-26 16:33:30 +000013import mimetools
14
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000015__all__ = ["MimeWriter"]
Guido van Rossumc75db0b1996-08-26 16:33:30 +000016
Brett Cannon90134c92007-05-30 20:46:26 +000017import warnings
18
19warnings.warn("the MimeWriter module is deprecated; use the email package instead",
20 DeprecationWarning, 2)
21
Guido van Rossumc75db0b1996-08-26 16:33:30 +000022class MimeWriter:
23
24 """Generic MIME writer.
25
26 Methods:
27
28 __init__()
29 addheader()
30 flushheaders()
31 startbody()
32 startmultipartbody()
33 nextpart()
34 lastpart()
35
36 A MIME writer is much more primitive than a MIME parser. It
37 doesn't seek around on the output file, and it doesn't use large
38 amounts of buffer space, so you have to write the parts in the
39 order they should occur on the output file. It does buffer the
40 headers you add, allowing you to rearrange their order.
Tim Peters07e99cb2001-01-14 23:47:14 +000041
Guido van Rossumc75db0b1996-08-26 16:33:30 +000042 General usage is:
43
44 f = <open the output file>
45 w = MimeWriter(f)
46 ...call w.addheader(key, value) 0 or more times...
47
48 followed by either:
49
50 f = w.startbody(content_type)
51 ...call f.write(data) for body data...
52
53 or:
54
55 w.startmultipartbody(subtype)
56 for each part:
57 subwriter = w.nextpart()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 ...use the subwriter's methods to create the subpart...
Guido van Rossumc75db0b1996-08-26 16:33:30 +000059 w.lastpart()
60
61 The subwriter is another MimeWriter instance, and should be
62 treated in the same way as the toplevel MimeWriter. This way,
63 writing recursive body parts is easy.
64
65 Warning: don't forget to call lastpart()!
66
67 XXX There should be more state so calls made in the wrong order
68 are detected.
69
70 Some special cases:
71
72 - startbody() just returns the file passed to the constructor;
73 but don't use this knowledge, as it may be changed.
74
75 - startmultipartbody() actually returns a file as well;
76 this can be used to write the initial 'if you can read this your
77 mailer is not MIME-aware' message.
78
79 - If you call flushheaders(), the headers accumulated so far are
80 written out (and forgotten); this is useful if you don't need a
81 body part at all, e.g. for a subpart of type message/rfc822
82 that's (mis)used to store some header-like information.
83
84 - Passing a keyword argument 'prefix=<flag>' to addheader(),
85 start*body() affects where the header is inserted; 0 means
86 append at the end, 1 means insert at the start; default is
87 append for addheader(), but insert for start*body(), which use
88 it to determine where the Content-Type header goes.
89
90 """
91
92 def __init__(self, fp):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000093 self._fp = fp
94 self._headers = []
Guido van Rossumc75db0b1996-08-26 16:33:30 +000095
96 def addheader(self, key, value, prefix=0):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000097 """Add a header line to the MIME message.
98
99 The key is the name of the header, where the value obviously provides
100 the value of the header. The optional argument prefix determines
101 where the header is inserted; 0 means append at the end, 1 means
102 insert at the start. The default is to append.
103
104 """
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000105 lines = value.split("\n")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000106 while lines and not lines[-1]: del lines[-1]
107 while lines and not lines[0]: del lines[0]
108 for i in range(1, len(lines)):
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000109 lines[i] = " " + lines[i].strip()
110 value = "\n".join(lines) + "\n"
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 line = key + ": " + value
112 if prefix:
113 self._headers.insert(0, line)
114 else:
115 self._headers.append(line)
Guido van Rossumc75db0b1996-08-26 16:33:30 +0000116
117 def flushheaders(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000118 """Writes out and forgets all headers accumulated so far.
119
120 This is useful if you don't need a body part at all; for example,
121 for a subpart of type message/rfc822 that's (mis)used to store some
122 header-like information.
123
124 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 self._fp.writelines(self._headers)
126 self._headers = []
Guido van Rossumc75db0b1996-08-26 16:33:30 +0000127
128 def startbody(self, ctype, plist=[], prefix=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000129 """Returns a file-like object for writing the body of the message.
130
131 The content-type is set to the provided ctype, and the optional
132 parameter, plist, provides additional parameters for the
133 content-type declaration. The optional argument prefix determines
134 where the header is inserted; 0 means append at the end, 1 means
135 insert at the start. The default is to insert at the start.
136
137 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000138 for name, value in plist:
139 ctype = ctype + ';\n %s=\"%s\"' % (name, value)
140 self.addheader("Content-Type", ctype, prefix=prefix)
141 self.flushheaders()
142 self._fp.write("\n")
143 return self._fp
Guido van Rossumc75db0b1996-08-26 16:33:30 +0000144
145 def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000146 """Returns a file-like object for writing the body of the message.
147
148 Additionally, this method initializes the multi-part code, where the
149 subtype parameter provides the multipart subtype, the boundary
150 parameter may provide a user-defined boundary specification, and the
151 plist parameter provides optional parameters for the subtype. The
152 optional argument, prefix, determines where the header is inserted;
153 0 means append at the end, 1 means insert at the start. The default
154 is to insert at the start. Subparts should be created using the
155 nextpart() method.
156
157 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000158 self._boundary = boundary or mimetools.choose_boundary()
159 return self.startbody("multipart/" + subtype,
160 [("boundary", self._boundary)] + plist,
161 prefix=prefix)
Guido van Rossumc75db0b1996-08-26 16:33:30 +0000162
163 def nextpart(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000164 """Returns a new instance of MimeWriter which represents an
165 individual part in a multipart message.
166
167 This may be used to write the part as well as used for creating
168 recursively complex multipart messages. The message must first be
169 initialized with the startmultipartbody() method before using the
170 nextpart() method.
171
172 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 self._fp.write("\n--" + self._boundary + "\n")
174 return self.__class__(self._fp)
Guido van Rossumc75db0b1996-08-26 16:33:30 +0000175
176 def lastpart(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000177 """This is used to designate the last part of a multipart message.
178
179 It should always be used when writing multipart messages.
180
181 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 self._fp.write("\n--" + self._boundary + "--\n")
Guido van Rossumc75db0b1996-08-26 16:33:30 +0000183
184
185if __name__ == '__main__':
Guido van Rossum5fd90681998-04-23 13:34:57 +0000186 import test.test_MimeWriter