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

Public Member Functions

def __init__
 
def set_debuglevel
 
def connect
 
def send
 
def putcmd
 
def getreply
 
def docmd
 
def helo
 
def ehlo
 
def has_extn
 
def help
 
def rset
 
def noop
 
def mail
 
def rcpt
 
def data
 
def verify
 
def expn
 
def login
 
def starttls
 
def sendmail
 
def close
 
def quit
 

Data Fields

 esmtp_features
 
 debuglevel
 
 sock
 
 does_esmtp
 

Static Public Attributes

int debuglevel = 0
 
 file = None
 
 helo_resp = None
 
 ehlo_resp = None
 
int does_esmtp = 0
 
 vrfy = verify
 

Detailed Description

This class manages a connection to an SMTP or ESMTP server.
SMTP Objects:
    SMTP objects have the following attributes:
        helo_resp
            This is the message given by the server in response to the
            most recent HELO command.

        ehlo_resp
            This is the message given by the server in response to the
            most recent EHLO command. This is usually multiline.

        does_esmtp
            This is a True value _after you do an EHLO command_, if the
            server supports ESMTP.

        esmtp_features
            This is a dictionary, which, if the server supports ESMTP,
            will _after you do an EHLO command_, contain the names of the
            SMTP service extensions this server supports, and their
            parameters (if any).

            Note, all extension names are mapped to lower case in the
            dictionary.

    See each method's docstrings for details.  In general, there is a
    method of the same name to perform each SMTP command.  There is also a
    method called 'sendmail' that will do an entire mail transaction.

Definition at line 188 of file smtplib.py.

Constructor & Destructor Documentation

def __init__ (   self,
  host = '',
  port = 0 
)
Initialize a new instance.

If specified, `host' is the name of the remote host to which to
connect.  If specified, `port' specifies the port to which to connect.
By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is raised
if the specified `host' doesn't respond correctly.

Definition at line 223 of file smtplib.py.

224  def __init__(self, host = '', port = 0):
225  """Initialize a new instance.
226 
227  If specified, `host' is the name of the remote host to which to
228  connect. If specified, `port' specifies the port to which to connect.
229  By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
230  if the specified `host' doesn't respond correctly.
231 
232  """
233  self.esmtp_features = {}
234  if host:
235  (code, msg) = self.connect(host, port)
236  if code != 220:
237  raise SMTPConnectError(code, msg)

Member Function Documentation

def close (   self)
Close the connection to the SMTP server.

Definition at line 657 of file smtplib.py.

References Chunk.file, POP3.file, FTP.file, NNTP.file, Class.file, Hook.file, SMTP.file, DumbWriter.file, MiniFieldStorage.file, Breakpoint.file, FieldStorage.file, HTTP.file, POP3.sock, FTP.sock, NNTP.sock, SMTP.sock, HTTPConnection.sock, and HTTPSConnection.sock.

658  def close(self):
659  """Close the connection to the SMTP server."""
660  if self.file:
661  self.file.close()
662  self.file = None
663  if self.sock:
664  self.sock.close()
665  self.sock = None
666 
def connect (   self,
  host = 'localhost',
  port = 0 
)
Connect to a host on a given port.

If the hostname ends with a colon (`:') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.

Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.

Definition at line 247 of file smtplib.py.

References HTTPResponse.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, and HTTP.debuglevel.

248  def connect(self, host='localhost', port = 0):
249  """Connect to a host on a given port.
250 
251  If the hostname ends with a colon (`:') followed by a number, and
252  there is no port specified, that suffix will be stripped off and the
253  number interpreted as the port number to use.
254 
255  Note: This method is automatically invoked by __init__, if a host is
256  specified during instantiation.
257 
258  """
259  if not port and (host.find(':') == host.rfind(':')):
260  i = host.rfind(':')
261  if i >= 0:
262  host, port = host[:i], host[i+1:]
263  try: port = int(port)
264  except ValueError:
265  raise socket.error, "nonnumeric port"
266  if not port: port = SMTP_PORT
267  if self.debuglevel > 0: print 'connect:', (host, port)
268  msg = "getaddrinfo returns an empty list"
269  self.sock = None
270  for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
271  af, socktype, proto, canonname, sa = res
272  try:
273  self.sock = socket.socket(af, socktype, proto)
274  if self.debuglevel > 0: print 'connect:', (host, port)
275  self.sock.connect(sa)
276  except socket.error, msg:
277  if self.debuglevel > 0: print 'connect fail:', (host, port)
278  if self.sock:
279  self.sock.close()
280  self.sock = None
281  continue
282  break
283  if not self.sock:
284  raise socket.error, msg
285  (code, msg) = self.getreply()
286  if self.debuglevel > 0: print "connect:", msg
287  return (code, msg)
def data (   self,
  msg 
)
SMTP 'DATA' command -- sends message data to server.

Automatically quotes lines beginning with a period per rfc821.
Raises SMTPDataError if there is an unexpected reply to the
DATA command; the return value from this method is the final
response code received when the all data is sent.

Definition at line 433 of file smtplib.py.

References HTTPResponse.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, HTTP.debuglevel, SMTP.getreply(), HTTP.getreply(), FTP.putcmd(), NNTP.putcmd(), SMTP.putcmd(), smtplib.quotedata(), SSLFakeSocket.send(), SMTP.send(), HTTPConnection.send(), dispatcher_with_send.send(), file_wrapper.send(), FakeSocket.send(), and HTTP.send.

434  def data(self,msg):
435  """SMTP 'DATA' command -- sends message data to server.
436 
437  Automatically quotes lines beginning with a period per rfc821.
438  Raises SMTPDataError if there is an unexpected reply to the
439  DATA command; the return value from this method is the final
440  response code received when the all data is sent.
441  """
442  self.putcmd("data")
443  (code,repl)=self.getreply()
444  if self.debuglevel >0 : print "data:", (code,repl)
445  if code != 354:
446  raise SMTPDataError(code,repl)
447  else:
448  q = quotedata(msg)
449  if q[-2:] != CRLF:
450  q = q + CRLF
451  q = q + "." + CRLF
452  self.send(q)
453  (code,msg)=self.getreply()
454  if self.debuglevel >0 : print "data:", (code,msg)
455  return (code,msg)
def docmd (   self,
  cmd,
  args = "" 
)
Send a command, and return its response code.

Definition at line 348 of file smtplib.py.

References SMTP.getreply(), HTTP.getreply(), FTP.putcmd(), NNTP.putcmd(), and SMTP.putcmd().

349  def docmd(self, cmd, args=""):
350  """Send a command, and return its response code."""
351  self.putcmd(cmd,args)
352  return self.getreply()
def ehlo (   self,
  name = '' 
)
SMTP 'ehlo' command.
Hostname to send for this command defaults to the FQDN of the local
host.

Definition at line 367 of file smtplib.py.

References FileWrapper.close(), Shelf.close(), Chunk.close(), _Subfile.close(), SGMLParser.close(), openrsrc.close(), SSLFakeSocket.close(), _Hqxcoderengine.close(), SSLFakeFile.close(), FileInput.close(), _Rlecoderengine.close(), HTTPResponse.close(), BinHex.close(), GzipFile.close(), _Hqxdecoderengine.close(), Aifc_read.close(), _Rledecoderengine.close(), HTTPConnection.close(), HexBin.close(), TestSGMLParser.close(), file_wrapper.close(), FTP.close(), SMTP.close(), HTTP.close(), SMTP.ehlo_resp, SMTP.esmtp_features, socket.getfqdn(), SMTP.getreply(), HTTP.getreply(), FTP.putcmd(), NNTP.putcmd(), and SMTP.putcmd().

368  def ehlo(self, name=''):
369  """ SMTP 'ehlo' command.
370  Hostname to send for this command defaults to the FQDN of the local
371  host.
372  """
373  self.esmtp_features = {}
374  if name:
375  self.putcmd("ehlo", name)
376  else:
377  self.putcmd("ehlo", socket.getfqdn())
378  (code,msg)=self.getreply()
379  # According to RFC1869 some (badly written)
380  # MTA's will disconnect on an ehlo. Toss an exception if
381  # that happens -ddm
382  if code == -1 and len(msg) == 0:
383  self.close()
384  raise SMTPServerDisconnected("Server not connected")
385  self.ehlo_resp=msg
386  if code != 250:
387  return (code,msg)
388  self.does_esmtp=1
389  #parse the ehlo response -ddm
390  resp=self.ehlo_resp.split('\n')
391  del resp[0]
392  for each in resp:
393  m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
394  if m:
395  feature=m.group("feature").lower()
396  params=m.string[m.end("feature"):].strip()
397  self.esmtp_features[feature]=params
398  return (code,msg)
def expn (   self,
  address 
)
SMTP 'verify' command -- checks for address validity.

Definition at line 463 of file smtplib.py.

References SMTP.getreply(), HTTP.getreply(), FTP.putcmd(), NNTP.putcmd(), SMTP.putcmd(), and smtplib.quoteaddr().

464  def expn(self, address):
465  """SMTP 'verify' command -- checks for address validity."""
466  self.putcmd("expn", quoteaddr(address))
467  return self.getreply()
def getreply (   self)
Get a reply from the server.

Returns a tuple consisting of:

  - server response code (e.g. '250', or such, if all goes well)
    Note: returns -1 if it can't read response code.

  - server response string corresponding to response code (multiline
    responses are converted to a single, multiline string).

Raises SMTPServerDisconnected if end-of-file is reached.

Definition at line 308 of file smtplib.py.

References FileWrapper.close(), Shelf.close(), Chunk.close(), _Subfile.close(), SGMLParser.close(), openrsrc.close(), SSLFakeSocket.close(), _Hqxcoderengine.close(), SSLFakeFile.close(), FileInput.close(), _Rlecoderengine.close(), HTTPResponse.close(), BinHex.close(), GzipFile.close(), _Hqxdecoderengine.close(), Aifc_read.close(), _Rledecoderengine.close(), HTTPConnection.close(), HexBin.close(), TestSGMLParser.close(), file_wrapper.close(), FTP.close(), SMTP.close(), HTTP.close(), HTTPResponse.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, HTTP.debuglevel, Chunk.file, POP3.file, FTP.file, NNTP.file, Class.file, Hook.file, SMTP.file, DumbWriter.file, MiniFieldStorage.file, Breakpoint.file, FieldStorage.file, HTTP.file, dospath.join(), and string.strip().

309  def getreply(self):
310  """Get a reply from the server.
311 
312  Returns a tuple consisting of:
313 
314  - server response code (e.g. '250', or such, if all goes well)
315  Note: returns -1 if it can't read response code.
316 
317  - server response string corresponding to response code (multiline
318  responses are converted to a single, multiline string).
319 
320  Raises SMTPServerDisconnected if end-of-file is reached.
321  """
322  resp=[]
323  if self.file is None:
324  self.file = self.sock.makefile('rb')
325  while 1:
326  line = self.file.readline()
327  if line == '':
328  self.close()
329  raise SMTPServerDisconnected("Connection unexpectedly closed")
330  if self.debuglevel > 0: print 'reply:', `line`
331  resp.append(line[4:].strip())
332  code=line[:3]
333  # Check that the error code is syntactically correct.
334  # Don't attempt to read a continuation line if it is broken.
335  try:
336  errcode = int(code)
337  except ValueError:
338  errcode = -1
339  break
340  # Check if multiline response.
341  if line[3:4]!="-":
342  break
343 
344  errmsg = "\n".join(resp)
345  if self.debuglevel > 0:
346  print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
347  return errcode, errmsg
def has_extn (   self,
  opt 
)
Does the server support a given SMTP service extension?

Definition at line 399 of file smtplib.py.

400  def has_extn(self, opt):
401  """Does the server support a given SMTP service extension?"""
402  return self.esmtp_features.has_key(opt.lower())
def helo (   self,
  name = '' 
)
SMTP 'helo' command.
Hostname to send for this command defaults to the FQDN of the local
host.

Definition at line 354 of file smtplib.py.

References socket.getfqdn(), SMTP.getreply(), HTTP.getreply(), SMTP.helo_resp, FTP.putcmd(), NNTP.putcmd(), and SMTP.putcmd().

355  def helo(self, name=''):
356  """SMTP 'helo' command.
357  Hostname to send for this command defaults to the FQDN of the local
358  host.
359  """
360  if name:
361  self.putcmd("helo", name)
362  else:
363  self.putcmd("helo", socket.getfqdn())
364  (code,msg)=self.getreply()
365  self.helo_resp=msg
366  return (code,msg)
def help (   self,
  args = '' 
)
SMTP 'help' command.
Returns help text from server.

Definition at line 403 of file smtplib.py.

References SMTP.getreply(), HTTP.getreply(), FTP.putcmd(), NNTP.putcmd(), and SMTP.putcmd().

404  def help(self, args=''):
405  """SMTP 'help' command.
406  Returns help text from server."""
407  self.putcmd("help", args)
408  return self.getreply()
def login (   self,
  user,
  password 
)
Log in on an SMTP server that requires authentication.

The arguments are:
    - user:     The user name to authenticate with.
    - password: The password for the authentication.

If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.

This method will return normally if the authentication was successful.

This method may raise the following exceptions:

 SMTPHeloError            The server didn't reply properly to
                  the helo greeting.
 SMTPAuthenticationError  The server didn't accept the username/
                  password combination.
 SMTPException            No suitable authentication method was
                  found.

Definition at line 470 of file smtplib.py.

References HTTPResponse.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, HTTP.debuglevel, base64.decodestring(), SMTP.docmd(), SMTP.ehlo(), SMTP.ehlo_resp, base64.encodestring(), SMTP.esmtp_features, SMTP.has_extn(), SMTP.helo(), SMTP.helo_resp, hmac.hexdigest(), and dospath.split().

471  def login(self, user, password):
472  """Log in on an SMTP server that requires authentication.
473 
474  The arguments are:
475  - user: The user name to authenticate with.
476  - password: The password for the authentication.
477 
478  If there has been no previous EHLO or HELO command this session, this
479  method tries ESMTP EHLO first.
480 
481  This method will return normally if the authentication was successful.
482 
483  This method may raise the following exceptions:
484 
485  SMTPHeloError The server didn't reply properly to
486  the helo greeting.
487  SMTPAuthenticationError The server didn't accept the username/
488  password combination.
489  SMTPException No suitable authentication method was
490  found.
491  """
492 
493  def encode_cram_md5(challenge, user, password):
494  challenge = base64.decodestring(challenge)
495  response = user + " " + hmac.HMAC(password, challenge).hexdigest()
496  return base64.encodestring(response)[:-1]
497 
498  def encode_plain(user, password):
499  return base64.encodestring("%s\0%s\0%s" %
500  (user, user, password))[:-1]
501 
502  AUTH_PLAIN = "PLAIN"
503  AUTH_CRAM_MD5 = "CRAM-MD5"
504 
505  if self.helo_resp is None and self.ehlo_resp is None:
506  if not (200 <= self.ehlo()[0] <= 299):
507  (code, resp) = self.helo()
508  if not (200 <= code <= 299):
509  raise SMTPHeloError(code, resp)
510 
511  if not self.has_extn("auth"):
512  raise SMTPException("SMTP AUTH extension not supported by server.")
513 
514  # Authentication methods the server supports:
515  authlist = self.esmtp_features["auth"].split()
516 
517  # List of authentication methods we support: from preferred to
518  # less preferred methods. Except for the purpose of testing the weaker
519  # ones, we prefer stronger methods like CRAM-MD5:
520  preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN]
521  #preferred_auths = [AUTH_PLAIN, AUTH_CRAM_MD5]
522 
523  # Determine the authentication method we'll use
524  authmethod = None
525  for method in preferred_auths:
526  if method in authlist:
527  authmethod = method
528  break
529  if self.debuglevel > 0: print "AuthMethod:", authmethod
530 
531  if authmethod == AUTH_CRAM_MD5:
532  (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
533  if code == 503:
534  # 503 == 'Error: already authenticated'
535  return (code, resp)
536  (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
537  elif authmethod == AUTH_PLAIN:
538  (code, resp) = self.docmd("AUTH",
539  AUTH_PLAIN + " " + encode_plain(user, password))
540  elif authmethod == None:
541  raise SMTPException("No suitable authentication method found.")
542  if code not in [235, 503]:
543  # 235 == 'Authentication successful'
544  # 503 == 'Error: already authenticated'
545  raise SMTPAuthenticationError(code, resp)
546  return (code, resp)
def mail (   self,
  sender,
  options = [] 
)
SMTP 'mail' command -- begins mail xfer session.

Definition at line 417 of file smtplib.py.

References SMTP.does_esmtp, SMTP.getreply(), HTTP.getreply(), dospath.join(), FTP.putcmd(), NNTP.putcmd(), SMTP.putcmd(), and smtplib.quoteaddr().

418  def mail(self,sender,options=[]):
419  """SMTP 'mail' command -- begins mail xfer session."""
420  optionlist = ''
421  if options and self.does_esmtp:
422  optionlist = ' ' + ' '.join(options)
423  self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
424  return self.getreply()
def noop (   self)
SMTP 'noop' command -- doesn't do anything :>

Definition at line 413 of file smtplib.py.

References SMTP.docmd().

414  def noop(self):
415  """SMTP 'noop' command -- doesn't do anything :>"""
416  return self.docmd("noop")
def putcmd (   self,
  cmd,
  args = "" 
)
Send a command to the server.

Definition at line 300 of file smtplib.py.

References SSLFakeSocket.send(), SMTP.send(), HTTPConnection.send(), dispatcher_with_send.send(), file_wrapper.send(), FakeSocket.send(), and HTTP.send.

301  def putcmd(self, cmd, args=""):
302  """Send a command to the server."""
303  if args == "":
304  str = '%s%s' % (cmd, CRLF)
305  else:
306  str = '%s %s%s' % (cmd, args, CRLF)
307  self.send(str)
def quit (   self)
Terminate the SMTP session.

Definition at line 667 of file smtplib.py.

References FileWrapper.close(), Shelf.close(), Chunk.close(), _Subfile.close(), SGMLParser.close(), openrsrc.close(), SSLFakeSocket.close(), _Hqxcoderengine.close(), SSLFakeFile.close(), FileInput.close(), _Rlecoderengine.close(), HTTPResponse.close(), BinHex.close(), GzipFile.close(), _Hqxdecoderengine.close(), Aifc_read.close(), _Rledecoderengine.close(), HTTPConnection.close(), HexBin.close(), TestSGMLParser.close(), file_wrapper.close(), FTP.close(), SMTP.close(), HTTP.close(), and SMTP.docmd().

668  def quit(self):
669  """Terminate the SMTP session."""
670  self.docmd("quit")
671  self.close()
672 
673 
674 # Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost.
def rcpt (   self,
  recip,
  options = [] 
)
SMTP 'rcpt' command -- indicates 1 recipient for this mail.

Definition at line 425 of file smtplib.py.

References SMTP.does_esmtp, SMTP.getreply(), HTTP.getreply(), dospath.join(), FTP.putcmd(), NNTP.putcmd(), SMTP.putcmd(), and smtplib.quoteaddr().

426  def rcpt(self,recip,options=[]):
427  """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
428  optionlist = ''
429  if options and self.does_esmtp:
430  optionlist = ' ' + ' '.join(options)
431  self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
432  return self.getreply()
def rset (   self)
SMTP 'rset' command -- resets session.

Definition at line 409 of file smtplib.py.

References SMTP.docmd().

410  def rset(self):
411  """SMTP 'rset' command -- resets session."""
412  return self.docmd("rset")
def send (   self,
  str 
)
Send `str' to the server.

Definition at line 288 of file smtplib.py.

References FileWrapper.close(), Shelf.close(), Chunk.close(), _Subfile.close(), SGMLParser.close(), openrsrc.close(), SSLFakeSocket.close(), _Hqxcoderengine.close(), SSLFakeFile.close(), FileInput.close(), _Rlecoderengine.close(), HTTPResponse.close(), BinHex.close(), GzipFile.close(), _Hqxdecoderengine.close(), Aifc_read.close(), _Rledecoderengine.close(), HTTPConnection.close(), HexBin.close(), TestSGMLParser.close(), file_wrapper.close(), FTP.close(), SMTP.close(), HTTP.close(), HTTPResponse.debuglevel, SMTP.debuglevel, HTTPConnection.debuglevel, HTTP.debuglevel, POP3.sock, FTP.sock, NNTP.sock, SMTP.sock, HTTPConnection.sock, and HTTPSConnection.sock.

289  def send(self, str):
290  """Send `str' to the server."""
291  if self.debuglevel > 0: print 'send:', `str`
292  if self.sock:
293  try:
294  self.sock.sendall(str)
295  except socket.error:
296  self.close()
297  raise SMTPServerDisconnected('Server not connected')
298  else:
299  raise SMTPServerDisconnected('please run connect() first')
def sendmail (   self,
  from_addr,
  to_addrs,
  msg,
  mail_options = [],
  rcpt_options = [] 
)
This command performs an entire mail transaction.

The arguments are:
    - from_addr    : The address sending this mail.
    - to_addrs     : A list of addresses to send this mail to.  A bare
             string will be treated as a list with 1 address.
    - msg          : The message to send.
    - mail_options : List of ESMTP options (such as 8bitmime) for the
             mail command.
    - rcpt_options : List of ESMTP options (such as DSN commands) for
             all the rcpt commands.

If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.  If the server does ESMTP, message size
and each of the specified options will be passed to it.  If EHLO
fails, HELO will be tried and ESMTP options suppressed.

This method will return normally if the mail is accepted for at least
one recipient.  It returns a dictionary, with one entry for each
recipient that was refused.  Each entry contains a tuple of the SMTP
error code and the accompanying error message sent by the server.

This method may raise the following exceptions:

 SMTPHeloError          The server didn't reply properly to
                the helo greeting.
 SMTPRecipientsRefused  The server rejected ALL recipients
                (no mail was sent).
 SMTPSenderRefused      The server didn't accept the from_addr.
 SMTPDataError          The server replied with an unexpected
                error code (other than a refusal of
                a recipient).

Note: the connection will be open even after an exception is raised.

Example:

 >>> import smtplib
 >>> s=smtplib.SMTP("localhost")
 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
 >>> msg = '''
 ... From: Me@my.org
 ... Subject: testin'...
 ...
 ... This is a test '''
 >>> s.sendmail("me@my.org",tolist,msg)
 { "three@three.org" : ( 550 ,"User unknown" ) }
 >>> s.quit()

In the above example, the message was accepted for delivery to three
of the four addresses, and one was rejected, with the error code
550.  If all addresses are accepted, then the method will return an
empty dictionary.

Definition at line 564 of file smtplib.py.

References UserDict.data, UserList.data, UserString.data, _localized_month.data, _localized_day.data, SubPattern.data, _Hqxcoderengine.data, WeakKeyDictionary.data, MutableString.data, _Rlecoderengine.data, Request.data, simple_producer.data, Binary.data, NewsManager.data, _Environ.data, Marshaller.data, SMTP.data(), FormContentDict.data, GUISimpleListPicker.listitem.data, SMTP.does_esmtp, SMTP.ehlo(), SMTP.ehlo_resp, SMTP.has_extn(), SMTP.helo(), SMTP.helo_resp, SMTP.mail(), SMTP.rcpt(), POP3.rset(), and SMTP.rset().

565  rcpt_options=[]):
566  """This command performs an entire mail transaction.
567 
568  The arguments are:
569  - from_addr : The address sending this mail.
570  - to_addrs : A list of addresses to send this mail to. A bare
571  string will be treated as a list with 1 address.
572  - msg : The message to send.
573  - mail_options : List of ESMTP options (such as 8bitmime) for the
574  mail command.
575  - rcpt_options : List of ESMTP options (such as DSN commands) for
576  all the rcpt commands.
577 
578  If there has been no previous EHLO or HELO command this session, this
579  method tries ESMTP EHLO first. If the server does ESMTP, message size
580  and each of the specified options will be passed to it. If EHLO
581  fails, HELO will be tried and ESMTP options suppressed.
582 
583  This method will return normally if the mail is accepted for at least
584  one recipient. It returns a dictionary, with one entry for each
585  recipient that was refused. Each entry contains a tuple of the SMTP
586  error code and the accompanying error message sent by the server.
587 
588  This method may raise the following exceptions:
589 
590  SMTPHeloError The server didn't reply properly to
591  the helo greeting.
592  SMTPRecipientsRefused The server rejected ALL recipients
593  (no mail was sent).
594  SMTPSenderRefused The server didn't accept the from_addr.
595  SMTPDataError The server replied with an unexpected
596  error code (other than a refusal of
597  a recipient).
598 
599  Note: the connection will be open even after an exception is raised.
600 
601  Example:
602 
603  >>> import smtplib
604  >>> s=smtplib.SMTP("localhost")
605  >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
606  >>> msg = '''
607  ... From: Me@my.org
608  ... Subject: testin'...
609  ...
610  ... This is a test '''
611  >>> s.sendmail("me@my.org",tolist,msg)
612  { "three@three.org" : ( 550 ,"User unknown" ) }
613  >>> s.quit()
614 
615  In the above example, the message was accepted for delivery to three
616  of the four addresses, and one was rejected, with the error code
617  550. If all addresses are accepted, then the method will return an
618  empty dictionary.
619 
620  """
621  if self.helo_resp is None and self.ehlo_resp is None:
622  if not (200 <= self.ehlo()[0] <= 299):
623  (code,resp) = self.helo()
624  if not (200 <= code <= 299):
625  raise SMTPHeloError(code, resp)
626  esmtp_opts = []
627  if self.does_esmtp:
628  # Hmmm? what's this? -ddm
629  # self.esmtp_features['7bit']=""
630  if self.has_extn('size'):
631  esmtp_opts.append("size=" + `len(msg)`)
632  for option in mail_options:
633  esmtp_opts.append(option)
634 
635  (code,resp) = self.mail(from_addr, esmtp_opts)
636  if code != 250:
637  self.rset()
638  raise SMTPSenderRefused(code, resp, from_addr)
639  senderrs={}
640  if isinstance(to_addrs, types.StringTypes):
641  to_addrs = [to_addrs]
642  for each in to_addrs:
643  (code,resp)=self.rcpt(each, rcpt_options)
644  if (code != 250) and (code != 251):
645  senderrs[each]=(code,resp)
646  if len(senderrs)==len(to_addrs):
647  # the server refused all our recipients
648  self.rset()
649  raise SMTPRecipientsRefused(senderrs)
650  (code,resp) = self.data(msg)
651  if code != 250:
652  self.rset()
653  raise SMTPDataError(code, resp)
654  #if we got here then somebody got our mail
655  return senderrs
656 
def set_debuglevel (   self,
  debuglevel 
)
Set the debug output level.

A non-false value results in debug messages for connection and for all
messages sent to and received from the server.

Definition at line 238 of file smtplib.py.

239  def set_debuglevel(self, debuglevel):
240  """Set the debug output level.
241 
242  A non-false value results in debug messages for connection and for all
243  messages sent to and received from the server.
244 
245  """
246  self.debuglevel = debuglevel
def starttls (   self,
  keyfile = None,
  certfile = None 
)
Puts the connection to the SMTP server into TLS mode.

If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.

Definition at line 547 of file smtplib.py.

References SMTP.docmd(), Chunk.file, POP3.file, FTP.file, NNTP.file, Class.file, Hook.file, SMTP.file, DumbWriter.file, MiniFieldStorage.file, Breakpoint.file, FieldStorage.file, HTTP.file, SMTP.sendmail(), POP3.sock, FTP.sock, NNTP.sock, SMTP.sock, HTTPConnection.sock, HTTPSConnection.sock, and socket.ssl().

548  def starttls(self, keyfile = None, certfile = None):
549  """Puts the connection to the SMTP server into TLS mode.
550 
551  If the server supports TLS, this will encrypt the rest of the SMTP
552  session. If you provide the keyfile and certfile parameters,
553  the identity of the SMTP server and client can be checked. This,
554  however, depends on whether the socket module really checks the
555  certificates.
556  """
557  (resp, reply) = self.docmd("STARTTLS")
558  if resp == 220:
559  sslobj = socket.ssl(self.sock, keyfile, certfile)
560  self.sock = SSLFakeSocket(self.sock, sslobj)
561  self.file = SSLFakeFile(sslobj)
562  return (resp, reply)
def verify (   self,
  address 
)
SMTP 'verify' command -- checks for address validity.

Definition at line 456 of file smtplib.py.

References SMTP.getreply(), HTTP.getreply(), FTP.putcmd(), NNTP.putcmd(), SMTP.putcmd(), and smtplib.quoteaddr().

457  def verify(self, address):
458  """SMTP 'verify' command -- checks for address validity."""
459  self.putcmd("vrfy", quoteaddr(address))
return self.getreply()

Field Documentation

int debuglevel = 0
static

Definition at line 217 of file smtplib.py.

debuglevel

Definition at line 245 of file smtplib.py.

int does_esmtp = 0
static

Definition at line 221 of file smtplib.py.

does_esmtp

Definition at line 387 of file smtplib.py.

ehlo_resp = None
static

Definition at line 220 of file smtplib.py.

esmtp_features

Definition at line 232 of file smtplib.py.

file = None
static

Definition at line 218 of file smtplib.py.

helo_resp = None
static

Definition at line 219 of file smtplib.py.

sock

Definition at line 268 of file smtplib.py.

vrfy = verify
static

Definition at line 461 of file smtplib.py.


The documentation for this class was generated from the following file: