blob: 886098ccf407c685d6d9944a02a6b56538e5d14b [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
89 while 1:
90 line = self.fp.readline()
91 if not line:
92 self.status = 'EOF in headers'
93 break
94 if self.islast(line):
95 break
96 elif headerseen and line[0] in ' \t':
97 # It's a continuation line.
98 list.append(line)
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +000099 elif regex.match('^[!-9;-~]+:', line) >= 0:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000100 # It's a header line.
101 list.append(line)
102 headerseen = 1
103 else:
104 # It's not a header line; stop here.
105 if not headerseen:
106 self.status = 'No headers'
107 else:
108 self.status = 'Bad header'
109 # Try to undo the read.
110 try:
111 self.fp.seek(-len(line), 1)
112 except IOError:
113 self.status = \
114 self.status + '; bad seek'
115 break
116
117
118 # Method to determine whether a line is a legal end of
119 # RFC-822 headers. You may override this method if your
Guido van Rossumb6775db1994-08-01 11:34:53 +0000120 # application wants to bend the rules, e.g. to strip trailing
121 # whitespace, or to recognise MH template separators
122 # ('--------'). For convenience (e.g. for code reading from
123 # sockets) a line consisting of \r\n also matches.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000124
125 def islast(self, line):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126 return line == '\n' or line == '\r\n'
Guido van Rossum01ca3361992-07-13 14:28:59 +0000127
128
129 # Look through the list of headers and find all lines matching
130 # a given header name (and their continuation lines).
131 # A list of the lines is returned, without interpretation.
132 # If the header does not occur, an empty list is returned.
133 # If the header occurs multiple times, all occurrences are
134 # returned. Case is not important in the header name.
135
136 def getallmatchingheaders(self, name):
137 name = string.lower(name) + ':'
138 n = len(name)
139 list = []
140 hit = 0
141 for line in self.headers:
142 if string.lower(line[:n]) == name:
143 hit = 1
144 elif line[:1] not in string.whitespace:
145 hit = 0
146 if hit:
147 list.append(line)
148 return list
149
150
151 # Similar, but return only the first matching header (and its
152 # continuation lines).
153
154 def getfirstmatchingheader(self, name):
155 name = string.lower(name) + ':'
156 n = len(name)
157 list = []
158 hit = 0
159 for line in self.headers:
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000160 if hit:
161 if line[:1] not in string.whitespace:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000162 break
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000163 elif string.lower(line[:n]) == name:
164 hit = 1
Guido van Rossum01ca3361992-07-13 14:28:59 +0000165 if hit:
166 list.append(line)
167 return list
168
169
170 # A higher-level interface to getfirstmatchingheader().
171 # Return a string containing the literal text of the header
172 # but with the keyword stripped. All leading, trailing and
173 # embedded whitespace is kept in the string, however.
174 # Return None if the header does not occur.
175
176 def getrawheader(self, name):
177 list = self.getfirstmatchingheader(name)
178 if not list:
179 return None
180 list[0] = list[0][len(name) + 1:]
181 return string.joinfields(list, '')
182
183
184 # Going one step further: also strip leading and trailing
185 # whitespace.
186
187 def getheader(self, name):
188 text = self.getrawheader(name)
189 if text == None:
190 return None
191 return string.strip(text)
192
193
Guido van Rossumb6775db1994-08-01 11:34:53 +0000194 # Retrieve a single address from a header as a tuple, e.g.
195 # ('Guido van Rossum', 'guido@cwi.nl').
Guido van Rossum01ca3361992-07-13 14:28:59 +0000196
Guido van Rossumb6775db1994-08-01 11:34:53 +0000197 def getaddr(self, name):
198 data = self.getheader(name)
199 if not data:
200 return None, None
201 return parseaddr(data)
Guido van Rossum01ca3361992-07-13 14:28:59 +0000202
Guido van Rossumb6775db1994-08-01 11:34:53 +0000203 # Retrieve a list of addresses from a header, where each
204 # address is a tuple as returned by getaddr().
Guido van Rossum01ca3361992-07-13 14:28:59 +0000205
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206 def getaddrlist(self, name):
207 # XXX This function is not really correct. The split
208 # on ',' might fail in the case of commas within
209 # quoted strings.
210 data = self.getheader(name)
211 if not data:
212 return []
213 data = string.splitfields(data, ',')
214 for i in range(len(data)):
215 data[i] = parseaddr(data[i])
216 return data
217
218 # Retrieve a date field from a header as a tuple compatible
219 # with time.mktime().
220
221 def getdate(self, name):
222 data = self.getheader(name)
223 if not data:
224 return None
225 return parsedate(data)
226
227
228 # Access as a dictionary (only finds first header of each type):
229
230 def __len__(self):
231 types = {}
232 for line in self.headers:
233 if line[0] in string.whitespace: continue
234 i = string.find(line, ':')
235 if i > 0:
236 name = string.lower(line[:i])
237 types[name] = None
238 return len(types)
239
240 def __getitem__(self, name):
241 value = self.getheader(name)
242 if value is None: raise KeyError, name
243 return value
244
245 def has_key(self, name):
246 value = self.getheader(name)
247 return value is not None
248
249 def keys(self):
250 types = {}
251 for line in self.headers:
252 if line[0] in string.whitespace: continue
253 i = string.find(line, ':')
254 if i > 0:
255 name = line[:i]
256 key = string.lower(name)
257 types[key] = name
258 return types.values()
259
260 def values(self):
261 values = []
262 for name in self.keys():
263 values.append(self[name])
264 return values
265
266 def items(self):
267 items = []
268 for name in self.keys():
269 items.append(name, self[name])
270 return items
Guido van Rossum01ca3361992-07-13 14:28:59 +0000271
272
273
274# Utility functions
275# -----------------
276
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277# XXX Should fix these to be really conformant.
278# XXX The inverses of the parse functions may also be useful.
279
Guido van Rossum01ca3361992-07-13 14:28:59 +0000280
281# Remove quotes from a string.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000282
283def unquote(str):
284 if len(str) > 1:
285 if str[0] == '"' and str[-1:] == '"':
286 return str[1:-1]
287 if str[0] == '<' and str[-1:] == '>':
288 return str[1:-1]
289 return str
Guido van Rossumb6775db1994-08-01 11:34:53 +0000290
291
292# Parse an address into (name, address) tuple
293
294def parseaddr(address):
295 # This is probably not perfect
296 address = string.strip(address)
297 # Case 1: part of the address is in <xx@xx> form.
298 pos = regex.search('<.*>', address)
299 if pos >= 0:
300 name = address[:pos]
301 address = address[pos:]
302 length = regex.match('<.*>', address)
303 name = name + address[length:]
304 address = address[:length]
305 else:
306 # Case 2: part of the address is in (comment) form
307 pos = regex.search('(.*)', address)
308 if pos >= 0:
309 name = address[pos:]
310 address = address[:pos]
311 length = regex.match('(.*)', name)
312 address = address + name[length:]
313 name = name[:length]
314 else:
315 # Case 3: neither. Only an address
316 name = ''
317 name = string.strip(name)
318 address = string.strip(address)
319 if address and address[0] == '<' and address[-1] == '>':
320 address = address[1:-1]
321 if name and name[0] == '(' and name[-1] == ')':
322 name = name[1:-1]
323 return name, address
324
325
326# Parse a date field
327
328_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
329 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
330
331def parsedate(data):
332 # XXX This completely ignores timezone matters at the moment...
333 data = string.split(data)
334 if data[0][-1] == ',':
335 # There's a dayname here. Skip it
336 del data[0]
337 if len(data) < 5:
338 return None
339 data = data[:5]
340 [dd, mm, yy, tm, tz] = data
341 if not mm in _monthnames:
342 return None
343 mm = _monthnames.index(mm)+1
344 tm = string.splitfields(tm, ':')
345 if len(tm) == 2:
346 [thh, tmm] = tm
347 tss = '0'
348 else:
349 [thh, tmm, tss] = tm
350 try:
351 yy = string.atoi(yy)
352 dd = string.atoi(dd)
353 thh = string.atoi(thh)
354 tmm = string.atoi(tmm)
355 tss = string.atoi(tss)
356 except string.atoi_error:
357 return None
358 tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0)
359 return tuple
360
361
362# When used as script, run a small test program.
363# The first command line argument must be a filename containing one
364# message in RFC-822 format.
365
366if __name__ == '__main__':
367 import sys
368 file = '/ufs/guido/Mail/drafts/,1'
369 if sys.argv[1:]: file = sys.argv[1]
370 f = open(file, 'r')
371 m = Message(f)
372 print 'From:', m.getaddr('from')
373 print 'To:', m.getaddrlist('to')
374 print 'Subject:', m.getheader('subject')
375 print 'Date:', m.getheader('date')
376 date = m.getdate('date')
377 if date:
378 print 'ParsedDate:', time.asctime(date)
379 else:
380 print 'ParsedDate:', None
381 m.rewindbody()
382 n = 0
383 while f.readline():
384 n = n + 1
385 print 'Lines:', n
386 print '-'*70
387 print 'len =', len(m)
388 if m.has_key('Date'): print 'Date =', m['Date']
389 if m.has_key('X-Nonsense'): pass
390 print 'keys =', m.keys()
391 print 'values =', m.values()
392 print 'items =', m.items()
393