PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/rfc822.py

http://github.com/IronLanguages/main
Python | 1016 lines | 972 code | 20 blank | 24 comment | 23 complexity | 786dc65cb945321f0fb28e51fd6c422b MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """RFC 2822 message manipulation.
  2. Note: This is only a very rough sketch of a full RFC-822 parser; in particular
  3. the tokenizing of addresses does not adhere to all the quoting rules.
  4. Note: RFC 2822 is a long awaited update to RFC 822. This module should
  5. conform to RFC 2822, and is thus mis-named (it's not worth renaming it). Some
  6. effort at RFC 2822 updates have been made, but a thorough audit has not been
  7. performed. Consider any RFC 2822 non-conformance to be a bug.
  8. RFC 2822: http://www.faqs.org/rfcs/rfc2822.html
  9. RFC 822 : http://www.faqs.org/rfcs/rfc822.html (obsolete)
  10. Directions for use:
  11. To create a Message object: first open a file, e.g.:
  12. fp = open(file, 'r')
  13. You can use any other legal way of getting an open file object, e.g. use
  14. sys.stdin or call os.popen(). Then pass the open file object to the Message()
  15. constructor:
  16. m = Message(fp)
  17. This class can work with any input object that supports a readline method. If
  18. the input object has seek and tell capability, the rewindbody method will
  19. work; also illegal lines will be pushed back onto the input stream. If the
  20. input object lacks seek but has an `unread' method that can push back a line
  21. of input, Message will use that to push back illegal lines. Thus this class
  22. can be used to parse messages coming from a buffered stream.
  23. The optional `seekable' argument is provided as a workaround for certain stdio
  24. libraries in which tell() discards buffered data before discovering that the
  25. lseek() system call doesn't work. For maximum portability, you should set the
  26. seekable argument to zero to prevent that initial \code{tell} when passing in
  27. an unseekable object such as a file object created from a socket object. If
  28. it is 1 on entry -- which it is by default -- the tell() method of the open
  29. file object is called once; if this raises an exception, seekable is reset to
  30. 0. For other nonzero values of seekable, this test is not made.
  31. To get the text of a particular header there are several methods:
  32. str = m.getheader(name)
  33. str = m.getrawheader(name)
  34. where name is the name of the header, e.g. 'Subject'. The difference is that
  35. getheader() strips the leading and trailing whitespace, while getrawheader()
  36. doesn't. Both functions retain embedded whitespace (including newlines)
  37. exactly as they are specified in the header, and leave the case of the text
  38. unchanged.
  39. For addresses and address lists there are functions
  40. realname, mailaddress = m.getaddr(name)
  41. list = m.getaddrlist(name)
  42. where the latter returns a list of (realname, mailaddr) tuples.
  43. There is also a method
  44. time = m.getdate(name)
  45. which parses a Date-like field and returns a time-compatible tuple,
  46. i.e. a tuple such as returned by time.localtime() or accepted by
  47. time.mktime().
  48. See the class definition for lower level access methods.
  49. There are also some utility functions here.
  50. """
  51. # Cleanup and extensions by Eric S. Raymond <esr@thyrsus.com>
  52. import time
  53. from warnings import warnpy3k
  54. warnpy3k("in 3.x, rfc822 has been removed in favor of the email package",
  55. stacklevel=2)
  56. __all__ = ["Message","AddressList","parsedate","parsedate_tz","mktime_tz"]
  57. _blanklines = ('\r\n', '\n') # Optimization for islast()
  58. class Message:
  59. """Represents a single RFC 2822-compliant message."""
  60. def __init__(self, fp, seekable = 1):
  61. """Initialize the class instance and read the headers."""
  62. if seekable == 1:
  63. # Exercise tell() to make sure it works
  64. # (and then assume seek() works, too)
  65. try:
  66. fp.tell()
  67. except (AttributeError, IOError):
  68. seekable = 0
  69. self.fp = fp
  70. self.seekable = seekable
  71. self.startofheaders = None
  72. self.startofbody = None
  73. #
  74. if self.seekable:
  75. try:
  76. self.startofheaders = self.fp.tell()
  77. except IOError:
  78. self.seekable = 0
  79. #
  80. self.readheaders()
  81. #
  82. if self.seekable:
  83. try:
  84. self.startofbody = self.fp.tell()
  85. except IOError:
  86. self.seekable = 0
  87. def rewindbody(self):
  88. """Rewind the file to the start of the body (if seekable)."""
  89. if not self.seekable:
  90. raise IOError, "unseekable file"
  91. self.fp.seek(self.startofbody)
  92. def readheaders(self):
  93. """Read header lines.
  94. Read header lines up to the entirely blank line that terminates them.
  95. The (normally blank) line that ends the headers is skipped, but not
  96. included in the returned list. If a non-header line ends the headers,
  97. (which is an error), an attempt is made to backspace over it; it is
  98. never included in the returned list.
  99. The variable self.status is set to the empty string if all went well,
  100. otherwise it is an error message. The variable self.headers is a
  101. completely uninterpreted list of lines contained in the header (so
  102. printing them will reproduce the header exactly as it appears in the
  103. file).
  104. """
  105. self.dict = {}
  106. self.unixfrom = ''
  107. self.headers = lst = []
  108. self.status = ''
  109. headerseen = ""
  110. firstline = 1
  111. startofline = unread = tell = None
  112. if hasattr(self.fp, 'unread'):
  113. unread = self.fp.unread
  114. elif self.seekable:
  115. tell = self.fp.tell
  116. while 1:
  117. if tell:
  118. try:
  119. startofline = tell()
  120. except IOError:
  121. startofline = tell = None
  122. self.seekable = 0
  123. line = self.fp.readline()
  124. if not line:
  125. self.status = 'EOF in headers'
  126. break
  127. # Skip unix From name time lines
  128. if firstline and line.startswith('From '):
  129. self.unixfrom = self.unixfrom + line
  130. continue
  131. firstline = 0
  132. if headerseen and line[0] in ' \t':
  133. # It's a continuation line.
  134. lst.append(line)
  135. x = (self.dict[headerseen] + "\n " + line.strip())
  136. self.dict[headerseen] = x.strip()
  137. continue
  138. elif self.iscomment(line):
  139. # It's a comment. Ignore it.
  140. continue
  141. elif self.islast(line):
  142. # Note! No pushback here! The delimiter line gets eaten.
  143. break
  144. headerseen = self.isheader(line)
  145. if headerseen:
  146. # It's a legal header line, save it.
  147. lst.append(line)
  148. self.dict[headerseen] = line[len(headerseen)+1:].strip()
  149. continue
  150. elif headerseen is not None:
  151. # An empty header name. These aren't allowed in HTTP, but it's
  152. # probably a benign mistake. Don't add the header, just keep
  153. # going.
  154. continue
  155. else:
  156. # It's not a header line; throw it back and stop here.
  157. if not self.dict:
  158. self.status = 'No headers'
  159. else:
  160. self.status = 'Non-header line where header expected'
  161. # Try to undo the read.
  162. if unread:
  163. unread(line)
  164. elif tell:
  165. self.fp.seek(startofline)
  166. else:
  167. self.status = self.status + '; bad seek'
  168. break
  169. def isheader(self, line):
  170. """Determine whether a given line is a legal header.
  171. This method should return the header name, suitably canonicalized.
  172. You may override this method in order to use Message parsing on tagged
  173. data in RFC 2822-like formats with special header formats.
  174. """
  175. i = line.find(':')
  176. if i > -1:
  177. return line[:i].lower()
  178. return None
  179. def islast(self, line):
  180. """Determine whether a line is a legal end of RFC 2822 headers.
  181. You may override this method if your application wants to bend the
  182. rules, e.g. to strip trailing whitespace, or to recognize MH template
  183. separators ('--------'). For convenience (e.g. for code reading from
  184. sockets) a line consisting of \\r\\n also matches.
  185. """
  186. return line in _blanklines
  187. def iscomment(self, line):
  188. """Determine whether a line should be skipped entirely.
  189. You may override this method in order to use Message parsing on tagged
  190. data in RFC 2822-like formats that support embedded comments or
  191. free-text data.
  192. """
  193. return False
  194. def getallmatchingheaders(self, name):
  195. """Find all header lines matching a given header name.
  196. Look through the list of headers and find all lines matching a given
  197. header name (and their continuation lines). A list of the lines is
  198. returned, without interpretation. If the header does not occur, an
  199. empty list is returned. If the header occurs multiple times, all
  200. occurrences are returned. Case is not important in the header name.
  201. """
  202. name = name.lower() + ':'
  203. n = len(name)
  204. lst = []
  205. hit = 0
  206. for line in self.headers:
  207. if line[:n].lower() == name:
  208. hit = 1
  209. elif not line[:1].isspace():
  210. hit = 0
  211. if hit:
  212. lst.append(line)
  213. return lst
  214. def getfirstmatchingheader(self, name):
  215. """Get the first header line matching name.
  216. This is similar to getallmatchingheaders, but it returns only the
  217. first matching header (and its continuation lines).
  218. """
  219. name = name.lower() + ':'
  220. n = len(name)
  221. lst = []
  222. hit = 0
  223. for line in self.headers:
  224. if hit:
  225. if not line[:1].isspace():
  226. break
  227. elif line[:n].lower() == name:
  228. hit = 1
  229. if hit:
  230. lst.append(line)
  231. return lst
  232. def getrawheader(self, name):
  233. """A higher-level interface to getfirstmatchingheader().
  234. Return a string containing the literal text of the header but with the
  235. keyword stripped. All leading, trailing and embedded whitespace is
  236. kept in the string, however. Return None if the header does not
  237. occur.
  238. """
  239. lst = self.getfirstmatchingheader(name)
  240. if not lst:
  241. return None
  242. lst[0] = lst[0][len(name) + 1:]
  243. return ''.join(lst)
  244. def getheader(self, name, default=None):
  245. """Get the header value for a name.
  246. This is the normal interface: it returns a stripped version of the
  247. header value for a given header name, or None if it doesn't exist.
  248. This uses the dictionary version which finds the *last* such header.
  249. """
  250. return self.dict.get(name.lower(), default)
  251. get = getheader
  252. def getheaders(self, name):
  253. """Get all values for a header.
  254. This returns a list of values for headers given more than once; each
  255. value in the result list is stripped in the same way as the result of
  256. getheader(). If the header is not given, return an empty list.
  257. """
  258. result = []
  259. current = ''
  260. have_header = 0
  261. for s in self.getallmatchingheaders(name):
  262. if s[0].isspace():
  263. if current:
  264. current = "%s\n %s" % (current, s.strip())
  265. else:
  266. current = s.strip()
  267. else:
  268. if have_header:
  269. result.append(current)
  270. current = s[s.find(":") + 1:].strip()
  271. have_header = 1
  272. if have_header:
  273. result.append(current)
  274. return result
  275. def getaddr(self, name):
  276. """Get a single address from a header, as a tuple.
  277. An example return value:
  278. ('Guido van Rossum', 'guido@cwi.nl')
  279. """
  280. # New, by Ben Escoto
  281. alist = self.getaddrlist(name)
  282. if alist:
  283. return alist[0]
  284. else:
  285. return (None, None)
  286. def getaddrlist(self, name):
  287. """Get a list of addresses from a header.
  288. Retrieves a list of addresses from a header, where each address is a
  289. tuple as returned by getaddr(). Scans all named headers, so it works
  290. properly with multiple To: or Cc: headers for example.
  291. """
  292. raw = []
  293. for h in self.getallmatchingheaders(name):
  294. if h[0] in ' \t':
  295. raw.append(h)
  296. else:
  297. if raw:
  298. raw.append(', ')
  299. i = h.find(':')
  300. if i > 0:
  301. addr = h[i+1:]
  302. raw.append(addr)
  303. alladdrs = ''.join(raw)
  304. a = AddressList(alladdrs)
  305. return a.addresslist
  306. def getdate(self, name):
  307. """Retrieve a date field from a header.
  308. Retrieves a date field from the named header, returning a tuple
  309. compatible with time.mktime().
  310. """
  311. try:
  312. data = self[name]
  313. except KeyError:
  314. return None
  315. return parsedate(data)
  316. def getdate_tz(self, name):
  317. """Retrieve a date field from a header as a 10-tuple.
  318. The first 9 elements make up a tuple compatible with time.mktime(),
  319. and the 10th is the offset of the poster's time zone from GMT/UTC.
  320. """
  321. try:
  322. data = self[name]
  323. except KeyError:
  324. return None
  325. return parsedate_tz(data)
  326. # Access as a dictionary (only finds *last* header of each type):
  327. def __len__(self):
  328. """Get the number of headers in a message."""
  329. return len(self.dict)
  330. def __getitem__(self, name):
  331. """Get a specific header, as from a dictionary."""
  332. return self.dict[name.lower()]
  333. def __setitem__(self, name, value):
  334. """Set the value of a header.
  335. Note: This is not a perfect inversion of __getitem__, because any
  336. changed headers get stuck at the end of the raw-headers list rather
  337. than where the altered header was.
  338. """
  339. del self[name] # Won't fail if it doesn't exist
  340. self.dict[name.lower()] = value
  341. text = name + ": " + value
  342. for line in text.split("\n"):
  343. self.headers.append(line + "\n")
  344. def __delitem__(self, name):
  345. """Delete all occurrences of a specific header, if it is present."""
  346. name = name.lower()
  347. if not name in self.dict:
  348. return
  349. del self.dict[name]
  350. name = name + ':'
  351. n = len(name)
  352. lst = []
  353. hit = 0
  354. for i in range(len(self.headers)):
  355. line = self.headers[i]
  356. if line[:n].lower() == name:
  357. hit = 1
  358. elif not line[:1].isspace():
  359. hit = 0
  360. if hit:
  361. lst.append(i)
  362. for i in reversed(lst):
  363. del self.headers[i]
  364. def setdefault(self, name, default=""):
  365. lowername = name.lower()
  366. if lowername in self.dict:
  367. return self.dict[lowername]
  368. else:
  369. text = name + ": " + default
  370. for line in text.split("\n"):
  371. self.headers.append(line + "\n")
  372. self.dict[lowername] = default
  373. return default
  374. def has_key(self, name):
  375. """Determine whether a message contains the named header."""
  376. return name.lower() in self.dict
  377. def __contains__(self, name):
  378. """Determine whether a message contains the named header."""
  379. return name.lower() in self.dict
  380. def __iter__(self):
  381. return iter(self.dict)
  382. def keys(self):
  383. """Get all of a message's header field names."""
  384. return self.dict.keys()
  385. def values(self):
  386. """Get all of a message's header field values."""
  387. return self.dict.values()
  388. def items(self):
  389. """Get all of a message's headers.
  390. Returns a list of name, value tuples.
  391. """
  392. return self.dict.items()
  393. def __str__(self):
  394. return ''.join(self.headers)
  395. # Utility functions
  396. # -----------------
  397. # XXX Should fix unquote() and quote() to be really conformant.
  398. # XXX The inverses of the parse functions may also be useful.
  399. def unquote(s):
  400. """Remove quotes from a string."""
  401. if len(s) > 1:
  402. if s.startswith('"') and s.endswith('"'):
  403. return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  404. if s.startswith('<') and s.endswith('>'):
  405. return s[1:-1]
  406. return s
  407. def quote(s):
  408. """Add quotes around a string."""
  409. return s.replace('\\', '\\\\').replace('"', '\\"')
  410. def parseaddr(address):
  411. """Parse an address into a (realname, mailaddr) tuple."""
  412. a = AddressList(address)
  413. lst = a.addresslist
  414. if not lst:
  415. return (None, None)
  416. return lst[0]
  417. class AddrlistClass:
  418. """Address parser class by Ben Escoto.
  419. To understand what this class does, it helps to have a copy of
  420. RFC 2822 in front of you.
  421. http://www.faqs.org/rfcs/rfc2822.html
  422. Note: this class interface is deprecated and may be removed in the future.
  423. Use rfc822.AddressList instead.
  424. """
  425. def __init__(self, field):
  426. """Initialize a new instance.
  427. `field' is an unparsed address header field, containing one or more
  428. addresses.
  429. """
  430. self.specials = '()<>@,:;.\"[]'
  431. self.pos = 0
  432. self.LWS = ' \t'
  433. self.CR = '\r\n'
  434. self.atomends = self.specials + self.LWS + self.CR
  435. # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it
  436. # is obsolete syntax. RFC 2822 requires that we recognize obsolete
  437. # syntax, so allow dots in phrases.
  438. self.phraseends = self.atomends.replace('.', '')
  439. self.field = field
  440. self.commentlist = []
  441. def gotonext(self):
  442. """Parse up to the start of the next address."""
  443. while self.pos < len(self.field):
  444. if self.field[self.pos] in self.LWS + '\n\r':
  445. self.pos = self.pos + 1
  446. elif self.field[self.pos] == '(':
  447. self.commentlist.append(self.getcomment())
  448. else: break
  449. def getaddrlist(self):
  450. """Parse all addresses.
  451. Returns a list containing all of the addresses.
  452. """
  453. result = []
  454. ad = self.getaddress()
  455. while ad:
  456. result += ad
  457. ad = self.getaddress()
  458. return result
  459. def getaddress(self):
  460. """Parse the next address."""
  461. self.commentlist = []
  462. self.gotonext()
  463. oldpos = self.pos
  464. oldcl = self.commentlist
  465. plist = self.getphraselist()
  466. self.gotonext()
  467. returnlist = []
  468. if self.pos >= len(self.field):
  469. # Bad email address technically, no domain.
  470. if plist:
  471. returnlist = [(' '.join(self.commentlist), plist[0])]
  472. elif self.field[self.pos] in '.@':
  473. # email address is just an addrspec
  474. # this isn't very efficient since we start over
  475. self.pos = oldpos
  476. self.commentlist = oldcl
  477. addrspec = self.getaddrspec()
  478. returnlist = [(' '.join(self.commentlist), addrspec)]
  479. elif self.field[self.pos] == ':':
  480. # address is a group
  481. returnlist = []
  482. fieldlen = len(self.field)
  483. self.pos += 1
  484. while self.pos < len(self.field):
  485. self.gotonext()
  486. if self.pos < fieldlen and self.field[self.pos] == ';':
  487. self.pos += 1
  488. break
  489. returnlist = returnlist + self.getaddress()
  490. elif self.field[self.pos] == '<':
  491. # Address is a phrase then a route addr
  492. routeaddr = self.getrouteaddr()
  493. if self.commentlist:
  494. returnlist = [(' '.join(plist) + ' (' + \
  495. ' '.join(self.commentlist) + ')', routeaddr)]
  496. else: returnlist = [(' '.join(plist), routeaddr)]
  497. else:
  498. if plist:
  499. returnlist = [(' '.join(self.commentlist), plist[0])]
  500. elif self.field[self.pos] in self.specials:
  501. self.pos += 1
  502. self.gotonext()
  503. if self.pos < len(self.field) and self.field[self.pos] == ',':
  504. self.pos += 1
  505. return returnlist
  506. def getrouteaddr(self):
  507. """Parse a route address (Return-path value).
  508. This method just skips all the route stuff and returns the addrspec.
  509. """
  510. if self.field[self.pos] != '<':
  511. return
  512. expectroute = 0
  513. self.pos += 1
  514. self.gotonext()
  515. adlist = ""
  516. while self.pos < len(self.field):
  517. if expectroute:
  518. self.getdomain()
  519. expectroute = 0
  520. elif self.field[self.pos] == '>':
  521. self.pos += 1
  522. break
  523. elif self.field[self.pos] == '@':
  524. self.pos += 1
  525. expectroute = 1
  526. elif self.field[self.pos] == ':':
  527. self.pos += 1
  528. else:
  529. adlist = self.getaddrspec()
  530. self.pos += 1
  531. break
  532. self.gotonext()
  533. return adlist
  534. def getaddrspec(self):
  535. """Parse an RFC 2822 addr-spec."""
  536. aslist = []
  537. self.gotonext()
  538. while self.pos < len(self.field):
  539. if self.field[self.pos] == '.':
  540. aslist.append('.')
  541. self.pos += 1
  542. elif self.field[self.pos] == '"':
  543. aslist.append('"%s"' % self.getquote())
  544. elif self.field[self.pos] in self.atomends:
  545. break
  546. else: aslist.append(self.getatom())
  547. self.gotonext()
  548. if self.pos >= len(self.field) or self.field[self.pos] != '@':
  549. return ''.join(aslist)
  550. aslist.append('@')
  551. self.pos += 1
  552. self.gotonext()
  553. return ''.join(aslist) + self.getdomain()
  554. def getdomain(self):
  555. """Get the complete domain name from an address."""
  556. sdlist = []
  557. while self.pos < len(self.field):
  558. if self.field[self.pos] in self.LWS:
  559. self.pos += 1
  560. elif self.field[self.pos] == '(':
  561. self.commentlist.append(self.getcomment())
  562. elif self.field[self.pos] == '[':
  563. sdlist.append(self.getdomainliteral())
  564. elif self.field[self.pos] == '.':
  565. self.pos += 1
  566. sdlist.append('.')
  567. elif self.field[self.pos] in self.atomends:
  568. break
  569. else: sdlist.append(self.getatom())
  570. return ''.join(sdlist)
  571. def getdelimited(self, beginchar, endchars, allowcomments = 1):
  572. """Parse a header fragment delimited by special characters.
  573. `beginchar' is the start character for the fragment. If self is not
  574. looking at an instance of `beginchar' then getdelimited returns the
  575. empty string.
  576. `endchars' is a sequence of allowable end-delimiting characters.
  577. Parsing stops when one of these is encountered.
  578. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
  579. within the parsed fragment.
  580. """
  581. if self.field[self.pos] != beginchar:
  582. return ''
  583. slist = ['']
  584. quote = 0
  585. self.pos += 1
  586. while self.pos < len(self.field):
  587. if quote == 1:
  588. slist.append(self.field[self.pos])
  589. quote = 0
  590. elif self.field[self.pos] in endchars:
  591. self.pos += 1
  592. break
  593. elif allowcomments and self.field[self.pos] == '(':
  594. slist.append(self.getcomment())
  595. continue # have already advanced pos from getcomment
  596. elif self.field[self.pos] == '\\':
  597. quote = 1
  598. else:
  599. slist.append(self.field[self.pos])
  600. self.pos += 1
  601. return ''.join(slist)
  602. def getquote(self):
  603. """Get a quote-delimited fragment from self's field."""
  604. return self.getdelimited('"', '"\r', 0)
  605. def getcomment(self):
  606. """Get a parenthesis-delimited fragment from self's field."""
  607. return self.getdelimited('(', ')\r', 1)
  608. def getdomainliteral(self):
  609. """Parse an RFC 2822 domain-literal."""
  610. return '[%s]' % self.getdelimited('[', ']\r', 0)
  611. def getatom(self, atomends=None):
  612. """Parse an RFC 2822 atom.
  613. Optional atomends specifies a different set of end token delimiters
  614. (the default is to use self.atomends). This is used e.g. in
  615. getphraselist() since phrase endings must not include the `.' (which
  616. is legal in phrases)."""
  617. atomlist = ['']
  618. if atomends is None:
  619. atomends = self.atomends
  620. while self.pos < len(self.field):
  621. if self.field[self.pos] in atomends:
  622. break
  623. else: atomlist.append(self.field[self.pos])
  624. self.pos += 1
  625. return ''.join(atomlist)
  626. def getphraselist(self):
  627. """Parse a sequence of RFC 2822 phrases.
  628. A phrase is a sequence of words, which are in turn either RFC 2822
  629. atoms or quoted-strings. Phrases are canonicalized by squeezing all
  630. runs of continuous whitespace into one space.
  631. """
  632. plist = []
  633. while self.pos < len(self.field):
  634. if self.field[self.pos] in self.LWS:
  635. self.pos += 1
  636. elif self.field[self.pos] == '"':
  637. plist.append(self.getquote())
  638. elif self.field[self.pos] == '(':
  639. self.commentlist.append(self.getcomment())
  640. elif self.field[self.pos] in self.phraseends:
  641. break
  642. else:
  643. plist.append(self.getatom(self.phraseends))
  644. return plist
  645. class AddressList(AddrlistClass):
  646. """An AddressList encapsulates a list of parsed RFC 2822 addresses."""
  647. def __init__(self, field):
  648. AddrlistClass.__init__(self, field)
  649. if field:
  650. self.addresslist = self.getaddrlist()
  651. else:
  652. self.addresslist = []
  653. def __len__(self):
  654. return len(self.addresslist)
  655. def __str__(self):
  656. return ", ".join(map(dump_address_pair, self.addresslist))
  657. def __add__(self, other):
  658. # Set union
  659. newaddr = AddressList(None)
  660. newaddr.addresslist = self.addresslist[:]
  661. for x in other.addresslist:
  662. if not x in self.addresslist:
  663. newaddr.addresslist.append(x)
  664. return newaddr
  665. def __iadd__(self, other):
  666. # Set union, in-place
  667. for x in other.addresslist:
  668. if not x in self.addresslist:
  669. self.addresslist.append(x)
  670. return self
  671. def __sub__(self, other):
  672. # Set difference
  673. newaddr = AddressList(None)
  674. for x in self.addresslist:
  675. if not x in other.addresslist:
  676. newaddr.addresslist.append(x)
  677. return newaddr
  678. def __isub__(self, other):
  679. # Set difference, in-place
  680. for x in other.addresslist:
  681. if x in self.addresslist:
  682. self.addresslist.remove(x)
  683. return self
  684. def __getitem__(self, index):
  685. # Make indexing, slices, and 'in' work
  686. return self.addresslist[index]
  687. def dump_address_pair(pair):
  688. """Dump a (name, address) pair in a canonicalized form."""
  689. if pair[0]:
  690. return '"' + pair[0] + '" <' + pair[1] + '>'
  691. else:
  692. return pair[1]
  693. # Parse a date field
  694. _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',
  695. 'aug', 'sep', 'oct', 'nov', 'dec',
  696. 'january', 'february', 'march', 'april', 'may', 'june', 'july',
  697. 'august', 'september', 'october', 'november', 'december']
  698. _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
  699. # The timezone table does not include the military time zones defined
  700. # in RFC822, other than Z. According to RFC1123, the description in
  701. # RFC822 gets the signs wrong, so we can't rely on any such time
  702. # zones. RFC1123 recommends that numeric timezone indicators be used
  703. # instead of timezone names.
  704. _timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
  705. 'AST': -400, 'ADT': -300, # Atlantic (used in Canada)
  706. 'EST': -500, 'EDT': -400, # Eastern
  707. 'CST': -600, 'CDT': -500, # Central
  708. 'MST': -700, 'MDT': -600, # Mountain
  709. 'PST': -800, 'PDT': -700 # Pacific
  710. }
  711. def parsedate_tz(data):
  712. """Convert a date string to a time tuple.
  713. Accounts for military timezones.
  714. """
  715. if not data:
  716. return None
  717. data = data.split()
  718. if data[0][-1] in (',', '.') or data[0].lower() in _daynames:
  719. # There's a dayname here. Skip it
  720. del data[0]
  721. else:
  722. # no space after the "weekday,"?
  723. i = data[0].rfind(',')
  724. if i >= 0:
  725. data[0] = data[0][i+1:]
  726. if len(data) == 3: # RFC 850 date, deprecated
  727. stuff = data[0].split('-')
  728. if len(stuff) == 3:
  729. data = stuff + data[1:]
  730. if len(data) == 4:
  731. s = data[3]
  732. i = s.find('+')
  733. if i > 0:
  734. data[3:] = [s[:i], s[i+1:]]
  735. else:
  736. data.append('') # Dummy tz
  737. if len(data) < 5:
  738. return None
  739. data = data[:5]
  740. [dd, mm, yy, tm, tz] = data
  741. mm = mm.lower()
  742. if not mm in _monthnames:
  743. dd, mm = mm, dd.lower()
  744. if not mm in _monthnames:
  745. return None
  746. mm = _monthnames.index(mm)+1
  747. if mm > 12: mm = mm - 12
  748. if dd[-1] == ',':
  749. dd = dd[:-1]
  750. i = yy.find(':')
  751. if i > 0:
  752. yy, tm = tm, yy
  753. if yy[-1] == ',':
  754. yy = yy[:-1]
  755. if not yy[0].isdigit():
  756. yy, tz = tz, yy
  757. if tm[-1] == ',':
  758. tm = tm[:-1]
  759. tm = tm.split(':')
  760. if len(tm) == 2:
  761. [thh, tmm] = tm
  762. tss = '0'
  763. elif len(tm) == 3:
  764. [thh, tmm, tss] = tm
  765. else:
  766. return None
  767. try:
  768. yy = int(yy)
  769. dd = int(dd)
  770. thh = int(thh)
  771. tmm = int(tmm)
  772. tss = int(tss)
  773. except ValueError:
  774. return None
  775. tzoffset = None
  776. tz = tz.upper()
  777. if tz in _timezones:
  778. tzoffset = _timezones[tz]
  779. else:
  780. try:
  781. tzoffset = int(tz)
  782. except ValueError:
  783. pass
  784. # Convert a timezone offset into seconds ; -0500 -> -18000
  785. if tzoffset:
  786. if tzoffset < 0:
  787. tzsign = -1
  788. tzoffset = -tzoffset
  789. else:
  790. tzsign = 1
  791. tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60)
  792. return (yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset)
  793. def parsedate(data):
  794. """Convert a time string to a time tuple."""
  795. t = parsedate_tz(data)
  796. if t is None:
  797. return t
  798. return t[:9]
  799. def mktime_tz(data):
  800. """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""
  801. if data[9] is None:
  802. # No zone info, so localtime is better assumption than GMT
  803. return time.mktime(data[:8] + (-1,))
  804. else:
  805. t = time.mktime(data[:8] + (0,))
  806. return t - data[9] - time.timezone
  807. def formatdate(timeval=None):
  808. """Returns time format preferred for Internet standards.
  809. Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
  810. According to RFC 1123, day and month names must always be in
  811. English. If not for that, this code could use strftime(). It
  812. can't because strftime() honors the locale and could generate
  813. non-English names.
  814. """
  815. if timeval is None:
  816. timeval = time.time()
  817. timeval = time.gmtime(timeval)
  818. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
  819. ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
  820. timeval[2],
  821. ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
  822. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
  823. timeval[0], timeval[3], timeval[4], timeval[5])
  824. # When used as script, run a small test program.
  825. # The first command line argument must be a filename containing one
  826. # message in RFC-822 format.
  827. if __name__ == '__main__':
  828. import sys, os
  829. file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
  830. if sys.argv[1:]: file = sys.argv[1]
  831. f = open(file, 'r')
  832. m = Message(f)
  833. print 'From:', m.getaddr('from')
  834. print 'To:', m.getaddrlist('to')
  835. print 'Subject:', m.getheader('subject')
  836. print 'Date:', m.getheader('date')
  837. date = m.getdate_tz('date')
  838. tz = date[-1]
  839. date = time.localtime(mktime_tz(date))
  840. if date:
  841. print 'ParsedDate:', time.asctime(date),
  842. hhmmss = tz
  843. hhmm, ss = divmod(hhmmss, 60)
  844. hh, mm = divmod(hhmm, 60)
  845. print "%+03d%02d" % (hh, mm),
  846. if ss: print ".%02d" % ss,
  847. print
  848. else:
  849. print 'ParsedDate:', None
  850. m.rewindbody()
  851. n = 0
  852. while f.readline():
  853. n += 1
  854. print 'Lines:', n
  855. print '-'*70
  856. print 'len =', len(m)
  857. if 'Date' in m: print 'Date =', m['Date']
  858. if 'X-Nonsense' in m: pass
  859. print 'keys =', m.keys()
  860. print 'values =', m.values()
  861. print 'items =', m.items()