Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
rfc822 Namespace Reference

Data Structures

class  Message
 
class  AddrlistClass
 
class  AddressList
 

Functions

def unquote
 
def quote
 
def parseaddr
 
def dump_address_pair
 
def parsedate_tz
 
def parsedate
 
def mktime_tz
 
def formatdate
 

Variables

list __all__ = ["Message","AddressList","parsedate","parsedate_tz","mktime_tz"]
 
tuple _blanklines = ('\r\n', '\n')
 
list _monthnames
 
list _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
 
dictionary _timezones
 
tuple file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
 
tuple f = open(file, 'r')
 
tuple m = Message(f)
 
tuple date = m.getdate_tz('date')
 
list tz = date[-1]
 
 hhmmss = tz
 
int n = 0
 

Detailed Description

RFC 2822 message manipulation.

Note: This is only a very rough sketch of a full RFC-822 parser; in particular
the tokenizing of addresses does not adhere to all the quoting rules.

Note: RFC 2822 is a long awaited update to RFC 822.  This module should
conform to RFC 2822, and is thus mis-named (it's not worth renaming it).  Some
effort at RFC 2822 updates have been made, but a thorough audit has not been
performed.  Consider any RFC 2822 non-conformance to be a bug.

    RFC 2822: http://www.faqs.org/rfcs/rfc2822.html
    RFC 822 : http://www.faqs.org/rfcs/rfc822.html (obsolete)

Directions for use:

To create a Message object: first open a file, e.g.:

  fp = open(file, 'r')

You can use any other legal way of getting an open file object, e.g. use
sys.stdin or call os.popen().  Then pass the open file object to the Message()
constructor:

  m = Message(fp)

This class can work with any input object that supports a readline method.  If
the input object has seek and tell capability, the rewindbody method will
work; also illegal lines will be pushed back onto the input stream.  If the
input object lacks seek but has an `unread' method that can push back a line
of input, Message will use that to push back illegal lines.  Thus this class
can be used to parse messages coming from a buffered stream.

The optional `seekable' argument is provided as a workaround for certain stdio
libraries in which tell() discards buffered data before discovering that the
lseek() system call doesn't work.  For maximum portability, you should set the
seekable argument to zero to prevent that initial \code{tell} when passing in
an unseekable object such as a a file object created from a socket object.  If
it is 1 on entry -- which it is by default -- the tell() method of the open
file object is called once; if this raises an exception, seekable is reset to
0.  For other nonzero values of seekable, this test is not made.

To get the text of a particular header there are several methods:

  str = m.getheader(name)
  str = m.getrawheader(name)

where name is the name of the header, e.g. 'Subject'.  The difference is that
getheader() strips the leading and trailing whitespace, while getrawheader()
doesn't.  Both functions retain embedded whitespace (including newlines)
exactly as they are specified in the header, and leave the case of the text
unchanged.

For addresses and address lists there are functions

  realname, mailaddress = m.getaddr(name)
  list = m.getaddrlist(name)

where the latter returns a list of (realname, mailaddr) tuples.

There is also a method

  time = m.getdate(name)

which parses a Date-like field and returns a time-compatible tuple,
i.e. a tuple such as returned by time.localtime() or accepted by
time.mktime().

See the class definition for lower level access methods.

There are also some utility functions here.

Function Documentation

def rfc822.dump_address_pair (   pair)
Dump a (name, address) pair in a canonicalized form.

Definition at line 830 of file rfc822.py.

831 def dump_address_pair(pair):
832  """Dump a (name, address) pair in a canonicalized form."""
833  if pair[0]:
834  return '"' + pair[0] + '" <' + pair[1] + '>'
835  else:
836  return pair[1]
837 
838 # Parse a date field
def rfc822.formatdate (   timeval = None)
Returns time format preferred for Internet standards.

Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123

According to RFC 1123, day and month names must always be in
English.  If not for that, this code could use strftime().  It
can't because strftime() honors the locale and could generated
non-English names.

Definition at line 958 of file rfc822.py.

959 def formatdate(timeval=None):
960  """Returns time format preferred for Internet standards.
961 
962  Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
963 
964  According to RFC 1123, day and month names must always be in
965  English. If not for that, this code could use strftime(). It
966  can't because strftime() honors the locale and could generated
967  non-English names.
968  """
969  if timeval is None:
970  timeval = time.time()
971  timeval = time.gmtime(timeval)
972  return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
973  ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][timeval[6]],
974  timeval[2],
975  ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
976  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][timeval[1]-1],
977  timeval[0], timeval[3], timeval[4], timeval[5])
978 
979 
980 # When used as script, run a small test program.
981 # The first command line argument must be a filename containing one
982 # message in RFC-822 format.
def rfc822.mktime_tz (   data)
Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.

Definition at line 949 of file rfc822.py.

950 def mktime_tz(data):
951  """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""
952  if data[9] is None:
953  # No zone info, so localtime is better assumption than GMT
954  return time.mktime(data[:8] + (-1,))
955  else:
956  t = time.mktime(data[:8] + (0,))
957  return t - data[9] - time.timezone
def rfc822.parseaddr (   address)
Parse an address into a (realname, mailaddr) tuple.

Definition at line 495 of file rfc822.py.

496 def parseaddr(address):
497  """Parse an address into a (realname, mailaddr) tuple."""
498  a = AddrlistClass(address)
499  list = a.getaddrlist()
500  if not list:
501  return (None, None)
502  else:
503  return list[0]
504 
def rfc822.parsedate (   data)
Convert a time string to a time tuple.

Definition at line 941 of file rfc822.py.

References parsedate_tz().

942 def parsedate(data):
943  """Convert a time string to a time tuple."""
944  t = parsedate_tz(data)
945  if type(t) == type( () ):
946  return t[:9]
947  else: return t
948 
def rfc822.parsedate_tz (   data)
Convert a date string to a time tuple.

Accounts for military timezones.

Definition at line 860 of file rfc822.py.

References sre_parse.isdigit(), string.lower(), and dospath.split().

861 def parsedate_tz(data):
862  """Convert a date string to a time tuple.
863 
864  Accounts for military timezones.
865  """
866  if not data:
867  return None
868  data = data.split()
869  if data[0][-1] in (',', '.') or data[0].lower() in _daynames:
870  # There's a dayname here. Skip it
871  del data[0]
872  if len(data) == 3: # RFC 850 date, deprecated
873  stuff = data[0].split('-')
874  if len(stuff) == 3:
875  data = stuff + data[1:]
876  if len(data) == 4:
877  s = data[3]
878  i = s.find('+')
879  if i > 0:
880  data[3:] = [s[:i], s[i+1:]]
881  else:
882  data.append('') # Dummy tz
883  if len(data) < 5:
884  return None
885  data = data[:5]
886  [dd, mm, yy, tm, tz] = data
887  mm = mm.lower()
888  if not mm in _monthnames:
889  dd, mm = mm, dd.lower()
890  if not mm in _monthnames:
891  return None
892  mm = _monthnames.index(mm)+1
893  if mm > 12: mm = mm - 12
894  if dd[-1] == ',':
895  dd = dd[:-1]
896  i = yy.find(':')
897  if i > 0:
898  yy, tm = tm, yy
899  if yy[-1] == ',':
900  yy = yy[:-1]
901  if not yy[0].isdigit():
902  yy, tz = tz, yy
903  if tm[-1] == ',':
904  tm = tm[:-1]
905  tm = tm.split(':')
906  if len(tm) == 2:
907  [thh, tmm] = tm
908  tss = '0'
909  elif len(tm) == 3:
910  [thh, tmm, tss] = tm
911  else:
912  return None
913  try:
914  yy = int(yy)
915  dd = int(dd)
916  thh = int(thh)
917  tmm = int(tmm)
918  tss = int(tss)
919  except ValueError:
920  return None
921  tzoffset = None
922  tz = tz.upper()
923  if _timezones.has_key(tz):
924  tzoffset = _timezones[tz]
925  else:
926  try:
927  tzoffset = int(tz)
928  except ValueError:
929  pass
930  # Convert a timezone offset into seconds ; -0500 -> -18000
931  if tzoffset:
932  if tzoffset < 0:
933  tzsign = -1
934  tzoffset = -tzoffset
935  else:
936  tzsign = 1
937  tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60)
938  tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset)
939  return tuple
940 
def rfc822.quote (   str)
Add quotes around a string.

Definition at line 490 of file rfc822.py.

References pydoc.replace().

491 def quote(str):
492  """Add quotes around a string."""
493  return str.replace('\\', '\\\\').replace('"', '\\"')
494 
def rfc822.unquote (   str)
Remove quotes from a string.

Definition at line 480 of file rfc822.py.

481 def unquote(str):
482  """Remove quotes from a string."""
483  if len(str) > 1:
484  if str[0] == '"' and str[-1:] == '"':
485  return str[1:-1]
486  if str[0] == '<' and str[-1:] == '>':
487  return str[1:-1]
488  return str
489 

Variable Documentation

list __all__ = ["Message","AddressList","parsedate","parsedate_tz","mktime_tz"]

Definition at line 76 of file rfc822.py.

tuple _blanklines = ('\r\n', '\n')

Definition at line 78 of file rfc822.py.

list _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']

Definition at line 843 of file rfc822.py.

list _monthnames
Initial value:
1 = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',
2  'aug', 'sep', 'oct', 'nov', 'dec',
3  'january', 'february', 'march', 'april', 'may', 'june', 'july',
4  'august', 'september', 'october', 'november', 'december']

Definition at line 839 of file rfc822.py.

dictionary _timezones
Initial value:
1 = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
2  'AST': -400, 'ADT': -300, # Atlantic (used in Canada)
3  'EST': -500, 'EDT': -400, # Eastern
4  'CST': -600, 'CDT': -500, # Central
5  'MST': -700, 'MDT': -600, # Mountain
6  'PST': -800, 'PDT': -700 # Pacific
7  }

Definition at line 851 of file rfc822.py.

tuple date = m.getdate_tz('date')

Definition at line 993 of file rfc822.py.

tuple f = open(file, 'r')

Definition at line 987 of file rfc822.py.

tuple file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')

Definition at line 985 of file rfc822.py.

hhmmss = tz

Definition at line 998 of file rfc822.py.

tuple m = Message(f)

Definition at line 988 of file rfc822.py.

int n = 0

Definition at line 1007 of file rfc822.py.

list tz = date[-1]

Definition at line 994 of file rfc822.py.