blob: d0e5bcbc9575c1e9e0a265983ddd2ea017b1d2da [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
Guido van Rossum9694fca1997-10-22 21:00:49 +000041import re
Guido van Rossum01ca3361992-07-13 14:28:59 +000042import string
Guido van Rossumb6775db1994-08-01 11:34:53 +000043import time
Guido van Rossum01ca3361992-07-13 14:28:59 +000044
45
Guido van Rossum92457b91995-06-22 19:06:57 +000046_blanklines = ('\r\n', '\n') # Optimization for islast()
47
48
Guido van Rossum01ca3361992-07-13 14:28:59 +000049class Message:
50
51 # Initialize the class instance and read the headers.
52
Guido van Rossum92457b91995-06-22 19:06:57 +000053 def __init__(self, fp, seekable = 1):
Guido van Rossum01ca3361992-07-13 14:28:59 +000054 self.fp = fp
Guido van Rossum92457b91995-06-22 19:06:57 +000055 self.seekable = seekable
56 self.startofheaders = None
57 self.startofbody = None
Guido van Rossum01ca3361992-07-13 14:28:59 +000058 #
Guido van Rossum92457b91995-06-22 19:06:57 +000059 if self.seekable:
60 try:
61 self.startofheaders = self.fp.tell()
62 except IOError:
63 self.seekable = 0
Guido van Rossum01ca3361992-07-13 14:28:59 +000064 #
65 self.readheaders()
66 #
Guido van Rossum92457b91995-06-22 19:06:57 +000067 if self.seekable:
68 try:
69 self.startofbody = self.fp.tell()
70 except IOError:
71 self.seekable = 0
Guido van Rossum01ca3361992-07-13 14:28:59 +000072
73
74 # Rewind the file to the start of the body (if seekable).
75
76 def rewindbody(self):
Guido van Rossum92457b91995-06-22 19:06:57 +000077 if not self.seekable:
78 raise IOError, "unseekable file"
Guido van Rossum01ca3361992-07-13 14:28:59 +000079 self.fp.seek(self.startofbody)
80
81
82 # Read header lines up to the entirely blank line that
83 # terminates them. The (normally blank) line that ends the
84 # headers is skipped, but not included in the returned list.
85 # If a non-header line ends the headers, (which is an error),
86 # an attempt is made to backspace over it; it is never
87 # included in the returned list.
88 #
89 # The variable self.status is set to the empty string if all
90 # went well, otherwise it is an error message.
91 # The variable self.headers is a completely uninterpreted list
92 # of lines contained in the header (so printing them will
93 # reproduce the header exactly as it appears in the file).
94
95 def readheaders(self):
Guido van Rossuma13edb41996-05-28 23:08:25 +000096 self.dict = {}
Guido van Rossum92457b91995-06-22 19:06:57 +000097 self.unixfrom = ''
Guido van Rossum01ca3361992-07-13 14:28:59 +000098 self.headers = list = []
99 self.status = ''
Guido van Rossuma13edb41996-05-28 23:08:25 +0000100 headerseen = ""
Jack Jansen3a15dca1995-06-13 11:19:48 +0000101 firstline = 1
Guido van Rossum01ca3361992-07-13 14:28:59 +0000102 while 1:
103 line = self.fp.readline()
104 if not line:
105 self.status = 'EOF in headers'
106 break
Jack Jansen3a15dca1995-06-13 11:19:48 +0000107 # Skip unix From name time lines
Jack Jansene5e2cdd1995-06-16 10:57:14 +0000108 if firstline and line[:5] == 'From ':
Guido van Rossum92457b91995-06-22 19:06:57 +0000109 self.unixfrom = self.unixfrom + line
Jack Jansen3a15dca1995-06-13 11:19:48 +0000110 continue
111 firstline = 0
Guido van Rossum01ca3361992-07-13 14:28:59 +0000112 if self.islast(line):
113 break
114 elif headerseen and line[0] in ' \t':
115 # It's a continuation line.
116 list.append(line)
Guido van Rossuma13edb41996-05-28 23:08:25 +0000117 x = (self.dict[headerseen] + "\n " +
118 string.strip(line))
119 self.dict[headerseen] = string.strip(x)
120 elif ':' in line:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000121 # It's a header line.
122 list.append(line)
Guido van Rossuma13edb41996-05-28 23:08:25 +0000123 i = string.find(line, ':')
124 headerseen = string.lower(line[:i])
125 self.dict[headerseen] = string.strip(
126 line[i+1:])
Guido van Rossum01ca3361992-07-13 14:28:59 +0000127 else:
128 # It's not a header line; stop here.
129 if not headerseen:
130 self.status = 'No headers'
131 else:
132 self.status = 'Bad header'
133 # Try to undo the read.
Guido van Rossum92457b91995-06-22 19:06:57 +0000134 if self.seekable:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000135 self.fp.seek(-len(line), 1)
Guido van Rossum92457b91995-06-22 19:06:57 +0000136 else:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000137 self.status = \
138 self.status + '; bad seek'
139 break
140
141
142 # Method to determine whether a line is a legal end of
143 # RFC-822 headers. You may override this method if your
Guido van Rossumb6775db1994-08-01 11:34:53 +0000144 # application wants to bend the rules, e.g. to strip trailing
145 # whitespace, or to recognise MH template separators
146 # ('--------'). For convenience (e.g. for code reading from
147 # sockets) a line consisting of \r\n also matches.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000148
149 def islast(self, line):
Guido van Rossum92457b91995-06-22 19:06:57 +0000150 return line in _blanklines
Guido van Rossum01ca3361992-07-13 14:28:59 +0000151
152
153 # Look through the list of headers and find all lines matching
154 # a given header name (and their continuation lines).
155 # A list of the lines is returned, without interpretation.
156 # If the header does not occur, an empty list is returned.
157 # If the header occurs multiple times, all occurrences are
158 # returned. Case is not important in the header name.
159
160 def getallmatchingheaders(self, name):
161 name = string.lower(name) + ':'
162 n = len(name)
163 list = []
164 hit = 0
165 for line in self.headers:
166 if string.lower(line[:n]) == name:
167 hit = 1
168 elif line[:1] not in string.whitespace:
169 hit = 0
170 if hit:
171 list.append(line)
172 return list
173
174
175 # Similar, but return only the first matching header (and its
176 # continuation lines).
177
178 def getfirstmatchingheader(self, name):
179 name = string.lower(name) + ':'
180 n = len(name)
181 list = []
182 hit = 0
183 for line in self.headers:
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000184 if hit:
185 if line[:1] not in string.whitespace:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000186 break
Guido van Rossum3f9a6ec1994-08-12 13:16:50 +0000187 elif string.lower(line[:n]) == name:
188 hit = 1
Guido van Rossum01ca3361992-07-13 14:28:59 +0000189 if hit:
190 list.append(line)
191 return list
192
193
194 # A higher-level interface to getfirstmatchingheader().
195 # Return a string containing the literal text of the header
196 # but with the keyword stripped. All leading, trailing and
197 # embedded whitespace is kept in the string, however.
198 # Return None if the header does not occur.
199
200 def getrawheader(self, name):
201 list = self.getfirstmatchingheader(name)
202 if not list:
203 return None
204 list[0] = list[0][len(name) + 1:]
205 return string.joinfields(list, '')
206
207
Guido van Rossuma13edb41996-05-28 23:08:25 +0000208 # The normal interface: return a stripped version of the
209 # header value with a name, or None if it doesn't exist. This
210 # uses the dictionary version which finds the *last* such
211 # header.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000212
213 def getheader(self, name):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000214 try:
215 return self.dict[string.lower(name)]
216 except KeyError:
Guido van Rossum01ca3361992-07-13 14:28:59 +0000217 return None
Guido van Rossum01ca3361992-07-13 14:28:59 +0000218
219
Guido van Rossumb6775db1994-08-01 11:34:53 +0000220 # Retrieve a single address from a header as a tuple, e.g.
221 # ('Guido van Rossum', 'guido@cwi.nl').
Guido van Rossum01ca3361992-07-13 14:28:59 +0000222
Guido van Rossumb6775db1994-08-01 11:34:53 +0000223 def getaddr(self, name):
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000224 # New, by Ben Escoto
225 alist = self.getaddrlist(name)
226 if alist:
227 return alist[0]
228 else:
229 return (None, None)
Guido van Rossum01ca3361992-07-13 14:28:59 +0000230
Guido van Rossumb6775db1994-08-01 11:34:53 +0000231 # Retrieve a list of addresses from a header, where each
232 # address is a tuple as returned by getaddr().
Guido van Rossum01ca3361992-07-13 14:28:59 +0000233
Guido van Rossumb6775db1994-08-01 11:34:53 +0000234 def getaddrlist(self, name):
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000235 # New, by Ben Escoto
Guido van Rossuma13edb41996-05-28 23:08:25 +0000236 try:
237 data = self[name]
238 except KeyError:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000239 return []
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000240 a = AddrlistClass(data)
241 return a.getaddrlist()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000242
243 # Retrieve a date field from a header as a tuple compatible
244 # with time.mktime().
245
246 def getdate(self, name):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000247 try:
248 data = self[name]
249 except KeyError:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000250 return None
251 return parsedate(data)
252
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000253 # Retrieve a date field from a header as a 10-tuple.
254 # The first 9 elements make up a tuple compatible
255 # with time.mktime(), and the 10th is the offset
256 # of the poster's time zone from GMT/UTC.
257
258 def getdate_tz(self, name):
259 try:
260 data = self[name]
261 except KeyError:
262 return None
263 return parsedate_tz(data)
264
Guido van Rossumb6775db1994-08-01 11:34:53 +0000265
Guido van Rossuma13edb41996-05-28 23:08:25 +0000266 # Access as a dictionary (only finds *last* header of each type):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000267
268 def __len__(self):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000269 return len(self.dict)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270
271 def __getitem__(self, name):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000272 return self.dict[string.lower(name)]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
274 def has_key(self, name):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000275 return self.dict.has_key(string.lower(name))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000276
277 def keys(self):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000278 return self.dict.keys()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279
280 def values(self):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000281 return self.dict.values()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282
283 def items(self):
Guido van Rossuma13edb41996-05-28 23:08:25 +0000284 return self.dict.items()
Guido van Rossum01ca3361992-07-13 14:28:59 +0000285
286
287
288# Utility functions
289# -----------------
290
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000291# XXX Should fix unquote() and quote() to be really conformant.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292# XXX The inverses of the parse functions may also be useful.
293
Guido van Rossum01ca3361992-07-13 14:28:59 +0000294
295# Remove quotes from a string.
Guido van Rossum01ca3361992-07-13 14:28:59 +0000296
297def unquote(str):
298 if len(str) > 1:
299 if str[0] == '"' and str[-1:] == '"':
300 return str[1:-1]
301 if str[0] == '<' and str[-1:] == '>':
302 return str[1:-1]
303 return str
Guido van Rossumb6775db1994-08-01 11:34:53 +0000304
305
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000306# Add quotes around a string.
Guido van Rossum7883e1d1997-09-15 14:12:54 +0000307
308def quote(str):
309 return '"%s"' % string.join(
310 string.split(
311 string.join(
312 string.split(str, '\\'),
313 '\\\\'),
314 '"'),
315 '\\"')
Guido van Rossumb6775db1994-08-01 11:34:53 +0000316
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000317
318# External interface to parse an address
319
Guido van Rossumb6775db1994-08-01 11:34:53 +0000320def parseaddr(address):
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000321 a = AddrlistClass(address)
322 list = a.getaddrlist()
323 if not list:
324 return (None, None)
325 else:
326 return list[0]
327
328
329# Address parser class by Ben Escoto
330
331class AddrlistClass:
332
333 def __init__(self, field):
334
335 self.specials = '()<>@,:;.\"[]'
336 self.pos = 0
337 self.LWS = ' \t'
338 self.CR = '\r'
339 self.atomends = self.specials + self.LWS + self.CR
340
341 self.field = field
342 self.commentlist = []
343
344
345 def gotonext(self):
346
347 while self.pos < len(self.field):
348 if self.field[self.pos] in self.LWS + '\n\r':
349 self.pos = self.pos + 1
350 elif self.field[self.pos] == '(':
351 self.commentlist.append(self.getcomment())
352 else: break
353
354 def getaddrlist(self):
355
356 ad = self.getaddress()
357 if ad:
358 return ad + self.getaddrlist()
359 else: return []
360
361 def getaddress(self):
362 self.commentlist = []
363 self.gotonext()
364
365 oldpos = self.pos
366 oldcl = self.commentlist
367 plist = self.getphraselist()
368
369 self.gotonext()
370 returnlist = []
371
372 if self.pos >= len(self.field):
373 # Bad email address technically, no domain.
374 if plist:
375 returnlist = [(string.join(self.commentlist), plist[0])]
376
377 elif self.field[self.pos] in '.@':
378 # email address is just an addrspec
379 # this isn't very efficient since we start over
380 self.pos = oldpos
381 self.commentlist = oldcl
382 addrspec = self.getaddrspec()
383 returnlist = [(string.join(self.commentlist), addrspec)]
384
385 elif self.field[self.pos] == ':':
386 # address is a group
387 returnlist = []
388
389 self.pos = self.pos + 1
390 while self.pos < len(self.field):
391 self.gotonext()
392 if self.field[self.pos] == ';':
393 self.pos = self.pos + 1
394 break
395 returnlist = returnlist + self.getaddress()
396
397 elif self.field[self.pos] == '<':
398 # Address is a phrase then a route addr
399 routeaddr = self.getrouteaddr()
400
401 if self.commentlist:
402 returnlist = [(string.join(plist) + ' (' + \
403 string.join(self.commentlist) + ')', routeaddr)]
404 else: returnlist = [(string.join(plist), routeaddr)]
405
Guido van Rossum7883e1d1997-09-15 14:12:54 +0000406 else:
Guido van Rossumbe7c45e1997-11-22 21:49:19 +0000407 if plist:
408 returnlist = [(string.join(self.commentlist), plist[0])]
409
410 self.gotonext()
411 if self.pos < len(self.field) and self.field[self.pos] == ',':
412 self.pos = self.pos + 1
413 return returnlist
414
415
416 def getrouteaddr(self):
417 # This just skips all the route stuff and returns the addrspec
418 if self.field[self.pos] != '<':
419 return
420
421 expectroute = 0
422 self.pos = self.pos + 1
423 self.gotonext()
424 while self.pos < len(self.field):
425 if expectroute:
426 self.getdomain()
427 expectroute = 0
428 elif self.field[self.pos] == '>':
429 self.pos = self.pos + 1
430 break
431 elif self.field[self.pos] == '@':
432 self.pos = self.pos + 1
433 expectroute = 1
434 elif self.field[self.pos] == ':':
435 self.pos = self.pos + 1
436 expectaddrspec = 1
437 else:
438 adlist = self.getaddrspec()
439 self.pos = self.pos + 1
440 break
441 self.gotonext()
442
443 return adlist
444
445
446 def getaddrspec(self):
447
448 aslist = []
449
450 self.gotonext()
451 while self.pos < len(self.field):
452 if self.field[self.pos] == '.':
453 aslist.append('.')
454 self.pos = self.pos + 1
455 elif self.field[self.pos] == '"':
456 aslist.append(self.getquote())
457 elif self.field[self.pos] in self.atomends:
458 break
459 else: aslist.append(self.getatom())
460 self.gotonext()
461
462 if self.pos >= len(self.field) or self.field[self.pos] != '@':
463 return string.join(aslist, '')
464
465 aslist.append('@')
466 self.pos = self.pos + 1
467 self.gotonext()
468 return string.join(aslist, '') + self.getdomain()
469
470
471 def getdomain(self):
472
473 sdlist = []
474 while self.pos < len(self.field):
475 if self.field[self.pos] in self.LWS:
476 self.pos = self.pos + 1
477 elif self.field[self.pos] == '(':
478 self.commentlist.append(self.getcomment())
479 elif self.field[self.pos] == '[':
480 sdlist.append(self.getdomainliteral())
481 elif self.field[self.pos] == '.':
482 self.pos = self.pos + 1
483 sdlist.append('.')
484 elif self.field[self.pos] in self.atomends:
485 break
486 else: sdlist.append(self.getatom())
487
488 return string.join(sdlist, '')
489
490
491 def getdelimited(self, beginchar, endchars, allowcomments = 1):
492
493 if self.field[self.pos] != beginchar:
494 return ''
495
496 slist = ['']
497 quote = 0
498 self.pos = self.pos + 1
499 while self.pos < len(self.field):
500 if quote == 1:
501 slist.append(self.field[self.pos])
502 quote = 0
503 elif self.field[self.pos] in endchars:
504 self.pos = self.pos + 1
505 break
506 elif allowcomments and self.field[self.pos] == '(':
507 slist.append(self.getcomment())
508 elif self.field[self.pos] == '\\':
509 quote = 1
510 else:
511 slist.append(self.field[self.pos])
512 self.pos = self.pos + 1
513
514 return string.join(slist, '')
515
516 def getquote(self):
517 return self.getdelimited('"', '"\r', 0)
518
519 def getcomment(self):
520 return self.getdelimited('(', ')\r', 1)
521
522 def getdomainliteral(self):
523 return self.getdelimited('[', ']\r', 0)
524
525
526 def getatom(self):
527
528 atomlist = ['']
529
530 while self.pos < len(self.field):
531 if self.field[self.pos] in self.atomends:
532 break
533 else: atomlist.append(self.field[self.pos])
534 self.pos = self.pos + 1
535
536 return string.join(atomlist, '')
537
538
539 def getphraselist(self):
540
541 plist = []
542
543 while self.pos < len(self.field):
544 if self.field[self.pos] in self.LWS:
545 self.pos = self.pos + 1
546 elif self.field[self.pos] == '"':
547 plist.append(self.getquote())
548 elif self.field[self.pos] == '(':
549 self.commentlist.append(self.getcomment())
550 elif self.field[self.pos] in self.atomends:
551 break
552 else: plist.append(self.getatom())
553
554 return plist
Guido van Rossumb6775db1994-08-01 11:34:53 +0000555
556
557# Parse a date field
558
559_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
560 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Guido van Rossum9a876a41997-07-25 15:20:52 +0000561_daynames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
Guido van Rossumb6775db1994-08-01 11:34:53 +0000562
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000563# The timezone table does not include the military time zones defined
564# in RFC822, other than Z. According to RFC1123, the description in
565# RFC822 gets the signs wrong, so we can't rely on any such time
566# zones. RFC1123 recommends that numeric timezone indicators be used
567# instead of timezone names.
568
569_timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
570 'AST': -400, 'ADT': -300, # Atlantic standard
571 'EST': -500, 'EDT': -400, # Eastern
572 'CST': -600, 'CDT':-500, # Centreal
573 'MST':-700, 'MDT':-600, # Mountain
574 'PST':-800, 'PDT':-700 # Pacific
575 }
576
577def parsedate_tz(data):
Guido van Rossumb6775db1994-08-01 11:34:53 +0000578 data = string.split(data)
Guido van Rossum9a876a41997-07-25 15:20:52 +0000579 if data[0][-1] == ',' or data[0] in _daynames:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000580 # There's a dayname here. Skip it
581 del data[0]
Guido van Rossumc17a2681996-12-27 15:42:35 +0000582 if len(data) == 3: # RFC 850 date, deprecated
583 stuff = string.split(data[0], '-')
584 if len(stuff) == 3:
585 data = stuff + data[1:]
Guido van Rossum85347411994-09-09 11:10:15 +0000586 if len(data) == 4:
587 s = data[3]
588 i = string.find(s, '+')
589 if i > 0:
590 data[3:] = [s[:i], s[i+1:]]
591 else:
592 data.append('') # Dummy tz
Guido van Rossumb6775db1994-08-01 11:34:53 +0000593 if len(data) < 5:
594 return None
595 data = data[:5]
596 [dd, mm, yy, tm, tz] = data
597 if not mm in _monthnames:
Guido van Rossum9a876a41997-07-25 15:20:52 +0000598 dd, mm, yy, tm, tz = mm, dd, tm, yy, tz
599 if not mm in _monthnames:
600 return None
Guido van Rossumb6775db1994-08-01 11:34:53 +0000601 mm = _monthnames.index(mm)+1
602 tm = string.splitfields(tm, ':')
603 if len(tm) == 2:
604 [thh, tmm] = tm
605 tss = '0'
606 else:
607 [thh, tmm, tss] = tm
608 try:
609 yy = string.atoi(yy)
610 dd = string.atoi(dd)
611 thh = string.atoi(thh)
612 tmm = string.atoi(tmm)
613 tss = string.atoi(tss)
614 except string.atoi_error:
615 return None
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000616 tzoffset=0
617 tz=string.upper(tz)
618 if _timezones.has_key(tz):
619 tzoffset=_timezones[tz]
620 else:
621 try:
622 tzoffset=string.atoi(tz)
623 except string.atoi_error:
624 pass
625 # Convert a timezone offset into seconds ; -0500 -> -18000
626 if tzoffset<0: tzsign=-1
627 else: tzsign=1
628 tzoffset=tzoffset*tzsign
629 tzoffset = tzsign * ( (tzoffset/100)*3600 + (tzoffset % 100)*60)
630 tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000631 return tuple
632
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000633def parsedate(data):
634 t=parsedate_tz(data)
635 if type(t)==type( () ):
636 return t[:9]
637 else: return t
638
Guido van Rossum6cdd7a01996-12-12 18:39:54 +0000639def mktime_tz(data):
640 """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
641
642 Minor glitch: this first interprets the first 8 elements as a
643 local time and then compensates for the timezone difference;
644 this may yield a slight error around daylight savings time
645 switch dates. Not enough to worry about for common use.
646
647 """
648 t = time.mktime(data[:8] + (0,))
649 return t + data[9] - time.timezone
Guido van Rossumb6775db1994-08-01 11:34:53 +0000650
651# When used as script, run a small test program.
652# The first command line argument must be a filename containing one
653# message in RFC-822 format.
654
655if __name__ == '__main__':
Guido van Rossum3534a891996-07-30 16:29:16 +0000656 import sys, os
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000657 file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
Guido van Rossumb6775db1994-08-01 11:34:53 +0000658 if sys.argv[1:]: file = sys.argv[1]
659 f = open(file, 'r')
660 m = Message(f)
661 print 'From:', m.getaddr('from')
662 print 'To:', m.getaddrlist('to')
663 print 'Subject:', m.getheader('subject')
664 print 'Date:', m.getheader('date')
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000665 date = m.getdate_tz('date')
Guido van Rossumb6775db1994-08-01 11:34:53 +0000666 if date:
Guido van Rossum27cb8a41996-11-20 22:12:26 +0000667 print 'ParsedDate:', time.asctime(date[:-1]),
668 hhmmss = date[-1]
669 hhmm, ss = divmod(hhmmss, 60)
670 hh, mm = divmod(hhmm, 60)
671 print "%+03d%02d" % (hh, mm),
672 if ss: print ".%02d" % ss,
673 print
Guido van Rossumb6775db1994-08-01 11:34:53 +0000674 else:
675 print 'ParsedDate:', None
676 m.rewindbody()
677 n = 0
678 while f.readline():
679 n = n + 1
680 print 'Lines:', n
681 print '-'*70
682 print 'len =', len(m)
683 if m.has_key('Date'): print 'Date =', m['Date']
684 if m.has_key('X-Nonsense'): pass
685 print 'keys =', m.keys()
686 print 'values =', m.values()
687 print 'items =', m.items()