blob: 0e9122fa139f5676c5a0df189cd4295dc9f29297 [file] [log] [blame]
Guido van Rossum01ca3361992-07-13 14:28:59 +00001# RFC-822 message manipulation class.
2#
3# XXX This is only a very rough sketch of a full RFC-822 parser;
Guido van Rossumb6775db1994-08-01 11:34:53 +00004# in particular the tokenizing of addresses does not adhere to all the
5# quoting rules.
Guido van Rossum01ca3361992-07-13 14:28:59 +00006#
7# Directions for use:
8#
9# To create a Message object: first open a file, e.g.:
10# fp = open(file, 'r')
11# (or use any other legal way of getting an open file object, e.g. use
12# sys.stdin or call os.popen()).
Guido van Rossum7bc817d1993-12-17 15:25:27 +000013# Then pass the open file object to the Message() constructor:
14# m = Message(fp)
Guido van Rossum01ca3361992-07-13 14:28:59 +000015#
16# To get the text of a particular header there are several methods:
17# str = m.getheader(name)
18# str = m.getrawheader(name)
19# where name is the name of the header, e.g. 'Subject'.
20# The difference is that getheader() strips the leading and trailing
21# whitespace, while getrawheader() doesn't. Both functions retain
22# embedded whitespace (including newlines) exactly as they are
23# specified in the header, and leave the case of the text unchanged.
24#
Guido van Rossumb6775db1994-08-01 11:34:53 +000025# For addresses and address lists there are functions
26# realname, mailaddress = m.getaddr(name) and
27# list = m.getaddrlist(name)
28# where the latter returns a list of (realname, mailaddr) tuples.
29#
30# There is also a method
31# time = m.getdate(name)
32# which parses a Date-like field and returns a time-compatible tuple,
33# i.e. a tuple such as returned by time.localtime() or accepted by
34# time.mktime().
35#
Guido van Rossum01ca3361992-07-13 14:28:59 +000036# See the class definition for lower level access methods.
37#
38# There are also some utility functions here.
39
40
41import regex
42import string
Guido van Rossumb6775db1994-08-01 11:34:53 +000043import time
Guido van Rossum01ca3361992-07-13 14:28:59 +000044
45
46class Message:
47
48 # Initialize the class instance and read the headers.
49
Guido van Rossum7bc817d1993-12-17 15:25:27 +000050 def __init__(self, fp):
Guido van Rossum01ca3361992-07-13 14:28:59 +000051 self.fp = fp
52 #
53 try:
54 self.startofheaders = self.fp.tell()
55 except IOError:
56 self.startofheaders = None
57 #
58 self.readheaders()
59 #
60 try:
61 self.startofbody = self.fp.tell()
62 except IOError:
63 self.startofbody = None
Guido van Rossum01ca3361992-07-13 14:28:59 +000064
65
66 # Rewind the file to the start of the body (if seekable).
67
68 def rewindbody(self):
69 self.fp.seek(self.startofbody)
70
71
72 # Read header lines up to the entirely blank line that
73 # terminates them. The (normally blank) line that ends the
74 # headers is skipped, but not included in the returned list.
75 # If a non-header line ends the headers, (which is an error),
76 # an attempt is made to backspace over it; it is never
77 # included in the returned list.
78 #
79 # The variable self.status is set to the empty string if all
80 # went well, otherwise it is an error message.
81 # The variable self.headers is a completely uninterpreted list
82 # of lines contained in the header (so printing them will
83 # reproduce the header exactly as it appears in the file).
84
85 def readheaders(self):
86 self.headers = list = []
87 self.status = ''
88 headerseen = 0
Jack Jansen3a15dca1995-06-13 11:19:48 +000089 firstline = 1
Guido van Rossum01ca3361992-07-13 14:28:59 +000090 while 1:
91 line = self.fp.readline()
92 if not line:
93 self.status = 'EOF in headers'
94 break
Jack Jansen3a15dca1995-06-13 11:19:48 +000095 # Skip unix From name time lines
Jack Jansene5e2cdd1995-06-16 10:57:14 +000096 if firstline and line[:5] == 'From ':
Jack Jansen3a15dca1995-06-13 11:19:48 +000097 continue
98 firstline = 0
Guido van Rossum01ca3361992-07-13 14:28:59 +000099 if self.islast(line):
100 break
101 elif headerseen and line[0] in ' \t':
102 # It's a continuation line.
103 list.append(line)
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000104 elif regex.match('^[!-9;-~]+:', line) >= 0:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000105 # It's a header line.
106 list.append(line)
107 headerseen = 1
108 else:
109 # It's not a header line; stop here.
110 if not headerseen:
111 self.status = 'No headers'
112 else:
113 self.status = 'Bad header'
114 # Try to undo the read.
115 try:
116 self.fp.seek(-len(line), 1)
117 except IOError:
118 self.status = \
119 self.status + '; bad seek'
120 break
121
122
123 # Method to determine whether a line is a legal end of
124 # RFC-822 headers. You may override this method if your
Guido van Rossumb6775db1994-08-01 11:34:53 +0000125 # application wants to bend the rules, e.g. to strip trailing
126 # whitespace, or to recognise MH template separators
127 # ('--------'). For convenience (e.g. for code reading from
128 # sockets) a line consisting of \r\n also matches.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000129
130 def islast(self, line):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000131 return line == '\n' or line == '\r\n'
Guido van Rossum01ca3361992-07-13 14:28:59 +0000132
133
134 # Look through the list of headers and find all lines matching
135 # a given header name (and their continuation lines).
136 # A list of the lines is returned, without interpretation.
137 # If the header does not occur, an empty list is returned.
138 # If the header occurs multiple times, all occurrences are
139 # returned. Case is not important in the header name.
140
141 def getallmatchingheaders(self, name):
142 name = string.lower(name) + ':'
143 n = len(name)
144 list = []
145 hit = 0
146 for line in self.headers:
147 if string.lower(line[:n]) == name:
148 hit = 1
149 elif line[:1] not in string.whitespace:
150 hit = 0
151 if hit:
152 list.append(line)
153 return list
154
155
156 # Similar, but return only the first matching header (and its
157 # continuation lines).
158
159 def getfirstmatchingheader(self, name):
160 name = string.lower(name) + ':'
161 n = len(name)
162 list = []
163 hit = 0
164 for line in self.headers:
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000165 if hit:
166 if line[:1] not in string.whitespace:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000167 break
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000168 elif string.lower(line[:n]) == name:
169 hit = 1
Guido van Rossum01ca3361992-07-13 14:28:59 +0000170 if hit:
171 list.append(line)
172 return list
173
174
175 # A higher-level interface to getfirstmatchingheader().
176 # Return a string containing the literal text of the header
177 # but with the keyword stripped. All leading, trailing and
178 # embedded whitespace is kept in the string, however.
179 # Return None if the header does not occur.
180
181 def getrawheader(self, name):
182 list = self.getfirstmatchingheader(name)
183 if not list:
184 return None
185 list[0] = list[0][len(name) + 1:]
186 return string.joinfields(list, '')
187
188
189 # Going one step further: also strip leading and trailing
190 # whitespace.
191
192 def getheader(self, name):
193 text = self.getrawheader(name)
194 if text == None:
195 return None
196 return string.strip(text)
197
198
Guido van Rossumb6775db1994-08-01 11:34:53 +0000199 # Retrieve a single address from a header as a tuple, e.g.
200 # ('Guido van Rossum', 'guido@cwi.nl').
Guido van Rossum01ca3361992-07-13 14:28:59 +0000201
Guido van Rossumb6775db1994-08-01 11:34:53 +0000202 def getaddr(self, name):
203 data = self.getheader(name)
204 if not data:
205 return None, None
206 return parseaddr(data)
Guido van Rossum01ca3361992-07-13 14:28:59 +0000207
Guido van Rossumb6775db1994-08-01 11:34:53 +0000208 # Retrieve a list of addresses from a header, where each
209 # address is a tuple as returned by getaddr().
Guido van Rossum01ca3361992-07-13 14:28:59 +0000210
Guido van Rossumb6775db1994-08-01 11:34:53 +0000211 def getaddrlist(self, name):
212 # XXX This function is not really correct. The split
213 # on ',' might fail in the case of commas within
214 # quoted strings.
215 data = self.getheader(name)
216 if not data:
217 return []
218 data = string.splitfields(data, ',')
219 for i in range(len(data)):
220 data[i] = parseaddr(data[i])
221 return data
222
223 # Retrieve a date field from a header as a tuple compatible
224 # with time.mktime().
225
226 def getdate(self, name):
227 data = self.getheader(name)
228 if not data:
229 return None
230 return parsedate(data)
231
232
233 # Access as a dictionary (only finds first header of each type):
234
235 def __len__(self):
236 types = {}
237 for line in self.headers:
238 if line[0] in string.whitespace: continue
239 i = string.find(line, ':')
240 if i > 0:
241 name = string.lower(line[:i])
242 types[name] = None
243 return len(types)
244
245 def __getitem__(self, name):
246 value = self.getheader(name)
247 if value is None: raise KeyError, name
248 return value
249
250 def has_key(self, name):
251 value = self.getheader(name)
252 return value is not None
253
254 def keys(self):
255 types = {}
256 for line in self.headers:
257 if line[0] in string.whitespace: continue
258 i = string.find(line, ':')
259 if i > 0:
260 name = line[:i]
261 key = string.lower(name)
262 types[key] = name
263 return types.values()
264
265 def values(self):
266 values = []
267 for name in self.keys():
268 values.append(self[name])
269 return values
270
271 def items(self):
272 items = []
273 for name in self.keys():
274 items.append(name, self[name])
275 return items
Guido van Rossum01ca3361992-07-13 14:28:59 +0000276
277
278
279# Utility functions
280# -----------------
281
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282# XXX Should fix these to be really conformant.
283# XXX The inverses of the parse functions may also be useful.
284
Guido van Rossum01ca3361992-07-13 14:28:59 +0000285
286# Remove quotes from a string.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000287
288def unquote(str):
289 if len(str) > 1:
290 if str[0] == '"' and str[-1:] == '"':
291 return str[1:-1]
292 if str[0] == '<' and str[-1:] == '>':
293 return str[1:-1]
294 return str
Guido van Rossumb6775db1994-08-01 11:34:53 +0000295
296
297# Parse an address into (name, address) tuple
298
299def parseaddr(address):
300 # This is probably not perfect
301 address = string.strip(address)
302 # Case 1: part of the address is in <xx@xx> form.
303 pos = regex.search('<.*>', address)
304 if pos >= 0:
305 name = address[:pos]
306 address = address[pos:]
307 length = regex.match('<.*>', address)
308 name = name + address[length:]
309 address = address[:length]
310 else:
311 # Case 2: part of the address is in (comment) form
312 pos = regex.search('(.*)', address)
313 if pos >= 0:
314 name = address[pos:]
315 address = address[:pos]
316 length = regex.match('(.*)', name)
317 address = address + name[length:]
318 name = name[:length]
319 else:
320 # Case 3: neither. Only an address
321 name = ''
322 name = string.strip(name)
323 address = string.strip(address)
324 if address and address[0] == '<' and address[-1] == '>':
325 address = address[1:-1]
326 if name and name[0] == '(' and name[-1] == ')':
327 name = name[1:-1]
328 return name, address
329
330
331# Parse a date field
332
333_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
334 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
335
336def parsedate(data):
Guido van Rossum85347411994-09-09 11:10:15 +0000337 # XXX This still mostly ignores timezone matters at the moment...
Guido van Rossumb6775db1994-08-01 11:34:53 +0000338 data = string.split(data)
339 if data[0][-1] == ',':
340 # There's a dayname here. Skip it
341 del data[0]
Guido van Rossum85347411994-09-09 11:10:15 +0000342 if len(data) == 4:
343 s = data[3]
344 i = string.find(s, '+')
345 if i > 0:
346 data[3:] = [s[:i], s[i+1:]]
347 else:
348 data.append('') # Dummy tz
Guido van Rossumb6775db1994-08-01 11:34:53 +0000349 if len(data) < 5:
350 return None
351 data = data[:5]
352 [dd, mm, yy, tm, tz] = data
353 if not mm in _monthnames:
354 return None
355 mm = _monthnames.index(mm)+1
356 tm = string.splitfields(tm, ':')
357 if len(tm) == 2:
358 [thh, tmm] = tm
359 tss = '0'
360 else:
361 [thh, tmm, tss] = tm
362 try:
363 yy = string.atoi(yy)
364 dd = string.atoi(dd)
365 thh = string.atoi(thh)
366 tmm = string.atoi(tmm)
367 tss = string.atoi(tss)
368 except string.atoi_error:
369 return None
370 tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0)
371 return tuple
372
373
374# When used as script, run a small test program.
375# The first command line argument must be a filename containing one
376# message in RFC-822 format.
377
378if __name__ == '__main__':
379 import sys
380 file = '/ufs/guido/Mail/drafts/,1'
381 if sys.argv[1:]: file = sys.argv[1]
382 f = open(file, 'r')
383 m = Message(f)
384 print 'From:', m.getaddr('from')
385 print 'To:', m.getaddrlist('to')
386 print 'Subject:', m.getheader('subject')
387 print 'Date:', m.getheader('date')
388 date = m.getdate('date')
389 if date:
390 print 'ParsedDate:', time.asctime(date)
391 else:
392 print 'ParsedDate:', None
393 m.rewindbody()
394 n = 0
395 while f.readline():
396 n = n + 1
397 print 'Lines:', n
398 print '-'*70
399 print 'len =', len(m)
400 if m.has_key('Date'): print 'Date =', m['Date']
401 if m.has_key('X-Nonsense'): pass
402 print 'keys =', m.keys()
403 print 'values =', m.values()
404 print 'items =', m.items()
405