Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions
smtplib.SMTP_SSL Class Reference
Inheritance diagram for smtplib.SMTP_SSL:
Inheritance graph
[legend]
Collaboration diagram for smtplib.SMTP_SSL:
Collaboration graph
[legend]

List of all members.

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 ehlo_or_helo_if_needed
def login
def starttls
def sendmail
def send_message
def close
def quit

Public Attributes

 keyfile
 certfile
 file
 debuglevel
 does_esmtp
 timeout
 esmtp_features
 local_hostname
 sock

Static Public Attributes

 default_port = SMTP_SSL_PORT
int debuglevel = 0
 helo_resp = None
string ehlo_msg = "ehlo"
 ehlo_resp = None
int does_esmtp = 0
 vrfy = verify

Private Member Functions

def _get_socket

Detailed Description

This is a subclass derived from SMTP that connects over an SSL encrypted
socket (to use this class you need a socket module that was compiled with SSL
support). If host is not specified, '' (the local host) is used. If port is
omitted, the standard SMTP-over-SSL port (465) is used. keyfile and certfile
are also optional - they can contain a PEM formatted private key and
certificate chain file for the SSL connection.

Definition at line 832 of file smtplib.py.


Constructor & Destructor Documentation

def smtplib.SMTP_SSL.__init__ (   self,
  host = '',
  port = 0,
  local_hostname = None,
  keyfile = None,
  certfile = None,
  timeout = socket._GLOBAL_DEFAULT_TIMEOUT 
)

Definition at line 845 of file smtplib.py.

00845 
00846                      timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
00847             self.keyfile = keyfile
00848             self.certfile = certfile
00849             SMTP.__init__(self, host, port, local_hostname, timeout)

Here is the caller graph for this function:


Member Function Documentation

def smtplib.SMTP_SSL._get_socket (   self,
  host,
  port,
  timeout 
) [private]

Reimplemented from smtplib.SMTP.

Definition at line 850 of file smtplib.py.

00850 
00851         def _get_socket(self, host, port, timeout):
00852             if self.debuglevel > 0:
00853                 print('connect:', (host, port), file=stderr)
00854             new_socket = socket.create_connection((host, port), timeout)
00855             new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile)
00856             self.file = SSLFakeFile(new_socket)
00857             return new_socket
00858 
    __all__.append("SMTP_SSL")

Here is the call graph for this function:

def smtplib.SMTP.close (   self) [inherited]
Close the connection to the SMTP server.

Definition at line 815 of file smtplib.py.

00815 
00816     def close(self):
00817         """Close the connection to the SMTP server."""
00818         if self.file:
00819             self.file.close()
00820         self.file = None
00821         if self.sock:
00822             self.sock.close()
00823         self.sock = None

Here is the caller graph for this function:

def smtplib.SMTP.connect (   self,
  host = 'localhost',
  port = 0 
) [inherited]
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.

Reimplemented in smtplib.LMTP.

Definition at line 296 of file smtplib.py.

00296 
00297     def connect(self, host='localhost', port=0):
00298         """Connect to a host on a given port.
00299 
00300         If the hostname ends with a colon (`:') followed by a number, and
00301         there is no port specified, that suffix will be stripped off and the
00302         number interpreted as the port number to use.
00303 
00304         Note: This method is automatically invoked by __init__, if a host is
00305         specified during instantiation.
00306 
00307         """
00308         if not port and (host.find(':') == host.rfind(':')):
00309             i = host.rfind(':')
00310             if i >= 0:
00311                 host, port = host[:i], host[i + 1:]
00312                 try:
00313                     port = int(port)
00314                 except ValueError:
00315                     raise socket.error("nonnumeric port")
00316         if not port:
00317             port = self.default_port
00318         if self.debuglevel > 0:
00319             print('connect:', (host, port), file=stderr)
00320         self.sock = self._get_socket(host, port, self.timeout)
00321         (code, msg) = self.getreply()
00322         if self.debuglevel > 0:
00323             print("connect:", msg, file=stderr)
00324         return (code, msg)

Here is the caller graph for this function:

def smtplib.SMTP.data (   self,
  msg 
) [inherited]
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.  If msg
is a string, lone '\r' and '\n' characters are converted to
'\r\n' characters.  If msg is bytes, it is transmitted as is.

Definition at line 493 of file smtplib.py.

00493 
00494     def data(self, msg):
00495         """SMTP 'DATA' command -- sends message data to server.
00496 
00497         Automatically quotes lines beginning with a period per rfc821.
00498         Raises SMTPDataError if there is an unexpected reply to the
00499         DATA command; the return value from this method is the final
00500         response code received when the all data is sent.  If msg
00501         is a string, lone '\r' and '\n' characters are converted to
00502         '\r\n' characters.  If msg is bytes, it is transmitted as is.
00503         """
00504         self.putcmd("data")
00505         (code, repl) = self.getreply()
00506         if self.debuglevel > 0:
00507             print("data:", (code, repl), file=stderr)
00508         if code != 354:
00509             raise SMTPDataError(code, repl)
00510         else:
00511             if isinstance(msg, str):
00512                 msg = _fix_eols(msg).encode('ascii')
00513             q = _quote_periods(msg)
00514             if q[-2:] != bCRLF:
00515                 q = q + bCRLF
00516             q = q + b"." + bCRLF
00517             self.send(q)
00518             (code, msg) = self.getreply()
00519             if self.debuglevel > 0:
00520                 print("data:", (code, msg), file=stderr)
00521             return (code, msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.docmd (   self,
  cmd,
  args = "" 
) [inherited]
Send a command, and return its response code.

Definition at line 392 of file smtplib.py.

00392 
00393     def docmd(self, cmd, args=""):
00394         """Send a command, and return its response code."""
00395         self.putcmd(cmd, args)
00396         return self.getreply()

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.ehlo (   self,
  name = '' 
) [inherited]
SMTP 'ehlo' command.
Hostname to send for this command defaults to the FQDN of the local
host.

Definition at line 408 of file smtplib.py.

00408 
00409     def ehlo(self, name=''):
00410         """ SMTP 'ehlo' command.
00411         Hostname to send for this command defaults to the FQDN of the local
00412         host.
00413         """
00414         self.esmtp_features = {}
00415         self.putcmd(self.ehlo_msg, name or self.local_hostname)
00416         (code, msg) = self.getreply()
00417         # According to RFC1869 some (badly written)
00418         # MTA's will disconnect on an ehlo. Toss an exception if
00419         # that happens -ddm
00420         if code == -1 and len(msg) == 0:
00421             self.close()
00422             raise SMTPServerDisconnected("Server not connected")
00423         self.ehlo_resp = msg
00424         if code != 250:
00425             return (code, msg)
00426         self.does_esmtp = 1
00427         #parse the ehlo response -ddm
00428         assert isinstance(self.ehlo_resp, bytes), repr(self.ehlo_resp)
00429         resp = self.ehlo_resp.decode("latin-1").split('\n')
00430         del resp[0]
00431         for each in resp:
00432             # To be able to communicate with as many SMTP servers as possible,
00433             # we have to take the old-style auth advertisement into account,
00434             # because:
00435             # 1) Else our SMTP feature parser gets confused.
00436             # 2) There are some servers that only advertise the auth methods we
00437             #    support using the old style.
00438             auth_match = OLDSTYLE_AUTH.match(each)
00439             if auth_match:
00440                 # This doesn't remove duplicates, but that's no problem
00441                 self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \
00442                         + " " + auth_match.groups(0)[0]
00443                 continue
00444 
00445             # RFC 1869 requires a space between ehlo keyword and parameters.
00446             # It's actually stricter, in that only spaces are allowed between
00447             # parameters, but were not going to check for that here.  Note
00448             # that the space isn't present if there are no parameters.
00449             m = re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?', each)
00450             if m:
00451                 feature = m.group("feature").lower()
00452                 params = m.string[m.end("feature"):].strip()
00453                 if feature == "auth":
00454                     self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \
00455                             + " " + params
00456                 else:
00457                     self.esmtp_features[feature] = params
00458         return (code, msg)

Here is the caller graph for this function:

def smtplib.SMTP.ehlo_or_helo_if_needed (   self) [inherited]
Call self.ehlo() and/or self.helo() if needed.

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

This method may raise the following exceptions:

 SMTPHeloError            The server didn't reply properly to
                  the helo greeting.

Definition at line 536 of file smtplib.py.

00536 
00537     def ehlo_or_helo_if_needed(self):
00538         """Call self.ehlo() and/or self.helo() if needed.
00539 
00540         If there has been no previous EHLO or HELO command this session, this
00541         method tries ESMTP EHLO first.
00542 
00543         This method may raise the following exceptions:
00544 
00545          SMTPHeloError            The server didn't reply properly to
00546                                   the helo greeting.
00547         """
00548         if self.helo_resp is None and self.ehlo_resp is None:
00549             if not (200 <= self.ehlo()[0] <= 299):
00550                 (code, resp) = self.helo()
00551                 if not (200 <= code <= 299):
00552                     raise SMTPHeloError(code, resp)

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.expn (   self,
  address 
) [inherited]
SMTP 'expn' command -- expands a mailing list.

Definition at line 529 of file smtplib.py.

00529 
00530     def expn(self, address):
00531         """SMTP 'expn' command -- expands a mailing list."""
00532         self.putcmd("expn", _addr_only(address))
00533         return self.getreply()

Here is the call graph for this function:

def smtplib.SMTP.getreply (   self) [inherited]
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 348 of file smtplib.py.

00348 
00349     def getreply(self):
00350         """Get a reply from the server.
00351 
00352         Returns a tuple consisting of:
00353 
00354           - server response code (e.g. '250', or such, if all goes well)
00355             Note: returns -1 if it can't read response code.
00356 
00357           - server response string corresponding to response code (multiline
00358             responses are converted to a single, multiline string).
00359 
00360         Raises SMTPServerDisconnected if end-of-file is reached.
00361         """
00362         resp = []
00363         if self.file is None:
00364             self.file = self.sock.makefile('rb')
00365         while 1:
00366             try:
00367                 line = self.file.readline()
00368             except socket.error:
00369                 line = ''
00370             if not line:
00371                 self.close()
00372                 raise SMTPServerDisconnected("Connection unexpectedly closed")
00373             if self.debuglevel > 0:
00374                 print('reply:', repr(line), file=stderr)
00375             resp.append(line[4:].strip(b' \t\r\n'))
00376             code = line[:3]
00377             # Check that the error code is syntactically correct.
00378             # Don't attempt to read a continuation line if it is broken.
00379             try:
00380                 errcode = int(code)
00381             except ValueError:
00382                 errcode = -1
00383                 break
00384             # Check if multiline response.
00385             if line[3:4] != b"-":
00386                 break
00387 
00388         errmsg = b"\n".join(resp)
00389         if self.debuglevel > 0:
00390             print('reply: retcode (%s); Msg: %s' % (errcode, errmsg), file=stderr)
00391         return errcode, errmsg

Here is the caller graph for this function:

def smtplib.SMTP.has_extn (   self,
  opt 
) [inherited]
Does the server support a given SMTP service extension?

Definition at line 459 of file smtplib.py.

00459 
00460     def has_extn(self, opt):
00461         """Does the server support a given SMTP service extension?"""
00462         return opt.lower() in self.esmtp_features

Here is the caller graph for this function:

def smtplib.SMTP.helo (   self,
  name = '' 
) [inherited]
SMTP 'helo' command.
Hostname to send for this command defaults to the FQDN of the local
host.

Definition at line 398 of file smtplib.py.

00398 
00399     def helo(self, name=''):
00400         """SMTP 'helo' command.
00401         Hostname to send for this command defaults to the FQDN of the local
00402         host.
00403         """
00404         self.putcmd("helo", name or self.local_hostname)
00405         (code, msg) = self.getreply()
00406         self.helo_resp = msg
00407         return (code, msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.help (   self,
  args = '' 
) [inherited]
SMTP 'help' command.
Returns help text from server.

Definition at line 463 of file smtplib.py.

00463 
00464     def help(self, args=''):
00465         """SMTP 'help' command.
00466         Returns help text from server."""
00467         self.putcmd("help", args)
00468         return self.getreply()[1]

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.login (   self,
  user,
  password 
) [inherited]
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 553 of file smtplib.py.

00553 
00554     def login(self, user, password):
00555         """Log in on an SMTP server that requires authentication.
00556 
00557         The arguments are:
00558             - user:     The user name to authenticate with.
00559             - password: The password for the authentication.
00560 
00561         If there has been no previous EHLO or HELO command this session, this
00562         method tries ESMTP EHLO first.
00563 
00564         This method will return normally if the authentication was successful.
00565 
00566         This method may raise the following exceptions:
00567 
00568          SMTPHeloError            The server didn't reply properly to
00569                                   the helo greeting.
00570          SMTPAuthenticationError  The server didn't accept the username/
00571                                   password combination.
00572          SMTPException            No suitable authentication method was
00573                                   found.
00574         """
00575 
00576         def encode_cram_md5(challenge, user, password):
00577             challenge = base64.decodebytes(challenge)
00578             response = user + " " + hmac.HMAC(password.encode('ascii'),
00579                                               challenge).hexdigest()
00580             return encode_base64(response.encode('ascii'), eol='')
00581 
00582         def encode_plain(user, password):
00583             s = "\0%s\0%s" % (user, password)
00584             return encode_base64(s.encode('ascii'), eol='')
00585 
00586         AUTH_PLAIN = "PLAIN"
00587         AUTH_CRAM_MD5 = "CRAM-MD5"
00588         AUTH_LOGIN = "LOGIN"
00589 
00590         self.ehlo_or_helo_if_needed()
00591 
00592         if not self.has_extn("auth"):
00593             raise SMTPException("SMTP AUTH extension not supported by server.")
00594 
00595         # Authentication methods the server claims to support
00596         advertised_authlist = self.esmtp_features["auth"].split()
00597 
00598         # List of authentication methods we support: from preferred to
00599         # less preferred methods. Except for the purpose of testing the weaker
00600         # ones, we prefer stronger methods like CRAM-MD5:
00601         preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]
00602 
00603         # We try the authentication methods the server advertises, but only the
00604         # ones *we* support. And in our preferred order.
00605         authlist = [auth for auth in preferred_auths if auth in advertised_authlist]
00606         if not authlist:
00607             raise SMTPException("No suitable authentication method found.")
00608 
00609         # Some servers advertise authentication methods they don't really
00610         # support, so if authentication fails, we continue until we've tried
00611         # all methods.
00612         for authmethod in authlist:
00613             if authmethod == AUTH_CRAM_MD5:
00614                 (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
00615                 if code == 334:
00616                     (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
00617             elif authmethod == AUTH_PLAIN:
00618                 (code, resp) = self.docmd("AUTH",
00619                     AUTH_PLAIN + " " + encode_plain(user, password))
00620             elif authmethod == AUTH_LOGIN:
00621                 (code, resp) = self.docmd("AUTH",
00622                     "%s %s" % (AUTH_LOGIN, encode_base64(user.encode('ascii'), eol='')))
00623                 if code == 334:
00624                     (code, resp) = self.docmd(encode_base64(password.encode('ascii'), eol=''))
00625 
00626             # 235 == 'Authentication successful'
00627             # 503 == 'Error: already authenticated'
00628             if code in (235, 503):
00629                 return (code, resp)
00630 
00631         # We could not login sucessfully. Return result of last attempt.
00632         raise SMTPAuthenticationError(code, resp)

Here is the call graph for this function:

def smtplib.SMTP.mail (   self,
  sender,
  options = [] 
) [inherited]
SMTP 'mail' command -- begins mail xfer session.

Definition at line 477 of file smtplib.py.

00477 
00478     def mail(self, sender, options=[]):
00479         """SMTP 'mail' command -- begins mail xfer session."""
00480         optionlist = ''
00481         if options and self.does_esmtp:
00482             optionlist = ' ' + ' '.join(options)
00483         self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
00484         return self.getreply()

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.noop (   self) [inherited]
SMTP 'noop' command -- doesn't do anything :>

Definition at line 473 of file smtplib.py.

00473 
00474     def noop(self):
00475         """SMTP 'noop' command -- doesn't do anything :>"""
00476         return self.docmd("noop")

Here is the call graph for this function:

def smtplib.SMTP.putcmd (   self,
  cmd,
  args = "" 
) [inherited]
Send a command to the server.

Definition at line 340 of file smtplib.py.

00340 
00341     def putcmd(self, cmd, args=""):
00342         """Send a command to the server."""
00343         if args == "":
00344             str = '%s%s' % (cmd, CRLF)
00345         else:
00346             str = '%s %s%s' % (cmd, args, CRLF)
00347         self.send(str)

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.quit (   self) [inherited]
Terminate the SMTP session.

Definition at line 824 of file smtplib.py.

00824 
00825     def quit(self):
00826         """Terminate the SMTP session."""
00827         res = self.docmd("quit")
00828         self.close()
00829         return res

Here is the caller graph for this function:

def smtplib.SMTP.rcpt (   self,
  recip,
  options = [] 
) [inherited]
SMTP 'rcpt' command -- indicates 1 recipient for this mail.

Definition at line 485 of file smtplib.py.

00485 
00486     def rcpt(self, recip, options=[]):
00487         """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
00488         optionlist = ''
00489         if options and self.does_esmtp:
00490             optionlist = ' ' + ' '.join(options)
00491         self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist))
00492         return self.getreply()

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.rset (   self) [inherited]
SMTP 'rset' command -- resets session.

Definition at line 469 of file smtplib.py.

00469 
00470     def rset(self):
00471         """SMTP 'rset' command -- resets session."""
00472         return self.docmd("rset")

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.send (   self,
  s 
) [inherited]
Send `s' to the server.

Definition at line 325 of file smtplib.py.

00325 
00326     def send(self, s):
00327         """Send `s' to the server."""
00328         if self.debuglevel > 0:
00329             print('send:', repr(s), file=stderr)
00330         if hasattr(self, 'sock') and self.sock:
00331             if isinstance(s, str):
00332                 s = s.encode("ascii")
00333             try:
00334                 self.sock.sendall(s)
00335             except socket.error:
00336                 self.close()
00337                 raise SMTPServerDisconnected('Server not connected')
00338         else:
00339             raise SMTPServerDisconnected('please run connect() first')

Here is the caller graph for this function:

def smtplib.SMTP.send_message (   self,
  msg,
  from_addr = None,
  to_addrs = None,
  mail_options = [],
  rcpt_options = {} 
) [inherited]
Converts message to a bytestring and passes it to sendmail.

The arguments are as for sendmail, except that msg is an
email.message.Message object.  If from_addr is None or to_addrs is
None, these arguments are taken from the headers of the Message as
described in RFC 2822 (a ValueError is raised if there is more than
one set of 'Resent-' headers).  Regardless of the values of from_addr and
to_addr, any Bcc field (or Resent-Bcc field, when the Message is a
resent) of the Message object won't be transmitted.  The Message
object is then serialized using email.generator.BytesGenerator and
sendmail is called to transmit the message.

Definition at line 764 of file smtplib.py.

00764 
00765                 mail_options=[], rcpt_options={}):
00766         """Converts message to a bytestring and passes it to sendmail.
00767 
00768         The arguments are as for sendmail, except that msg is an
00769         email.message.Message object.  If from_addr is None or to_addrs is
00770         None, these arguments are taken from the headers of the Message as
00771         described in RFC 2822 (a ValueError is raised if there is more than
00772         one set of 'Resent-' headers).  Regardless of the values of from_addr and
00773         to_addr, any Bcc field (or Resent-Bcc field, when the Message is a
00774         resent) of the Message object won't be transmitted.  The Message
00775         object is then serialized using email.generator.BytesGenerator and
00776         sendmail is called to transmit the message.
00777 
00778         """
00779         # 'Resent-Date' is a mandatory field if the Message is resent (RFC 2822
00780         # Section 3.6.6). In such a case, we use the 'Resent-*' fields.  However,
00781         # if there is more than one 'Resent-' block there's no way to
00782         # unambiguously determine which one is the most recent in all cases,
00783         # so rather than guess we raise a ValueError in that case.
00784         #
00785         # TODO implement heuristics to guess the correct Resent-* block with an
00786         # option allowing the user to enable the heuristics.  (It should be
00787         # possible to guess correctly almost all of the time.)
00788         resent =msg.get_all('Resent-Date')
00789         if resent is None:
00790             header_prefix = ''
00791         elif len(resent) == 1:
00792             header_prefix = 'Resent-'
00793         else:
00794             raise ValueError("message has more than one 'Resent-' header block")
00795         if from_addr is None:
00796             # Prefer the sender field per RFC 2822:3.6.2.
00797             from_addr = (msg[header_prefix+'Sender']
00798                            if (header_prefix+'Sender') in msg
00799                            else msg[header_prefix+'From'])
00800         if to_addrs is None:
00801             addr_fields = [f for f in (msg[header_prefix+'To'],
00802                                        msg[header_prefix+'Bcc'],
00803                                        msg[header_prefix+'Cc']) if f is not None]
00804             to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
00805         # Make a local copy so we can delete the bcc headers.
00806         msg_copy = copy.copy(msg)
00807         del msg_copy['Bcc']
00808         del msg_copy['Resent-Bcc']
00809         with io.BytesIO() as bytesmsg:
00810             g = email.generator.BytesGenerator(bytesmsg)
00811             g.flatten(msg_copy, linesep='\r\n')
00812             flatmsg = bytesmsg.getvalue()
00813         return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
00814                              rcpt_options)

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.sendmail (   self,
  from_addr,
  to_addrs,
  msg,
  mail_options = [],
  rcpt_options = [] 
) [inherited]
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.

msg may be a string containing characters in the ASCII range, or a byte
string.  A string is encoded to bytes using the ascii codec, and lone
\\r and \\n characters are converted to \\r\\n characters.

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 670 of file smtplib.py.

00670 
00671                  rcpt_options=[]):
00672         """This command performs an entire mail transaction.
00673 
00674         The arguments are:
00675             - from_addr    : The address sending this mail.
00676             - to_addrs     : A list of addresses to send this mail to.  A bare
00677                              string will be treated as a list with 1 address.
00678             - msg          : The message to send.
00679             - mail_options : List of ESMTP options (such as 8bitmime) for the
00680                              mail command.
00681             - rcpt_options : List of ESMTP options (such as DSN commands) for
00682                              all the rcpt commands.
00683 
00684         msg may be a string containing characters in the ASCII range, or a byte
00685         string.  A string is encoded to bytes using the ascii codec, and lone
00686         \\r and \\n characters are converted to \\r\\n characters.
00687 
00688         If there has been no previous EHLO or HELO command this session, this
00689         method tries ESMTP EHLO first.  If the server does ESMTP, message size
00690         and each of the specified options will be passed to it.  If EHLO
00691         fails, HELO will be tried and ESMTP options suppressed.
00692 
00693         This method will return normally if the mail is accepted for at least
00694         one recipient.  It returns a dictionary, with one entry for each
00695         recipient that was refused.  Each entry contains a tuple of the SMTP
00696         error code and the accompanying error message sent by the server.
00697 
00698         This method may raise the following exceptions:
00699 
00700          SMTPHeloError          The server didn't reply properly to
00701                                 the helo greeting.
00702          SMTPRecipientsRefused  The server rejected ALL recipients
00703                                 (no mail was sent).
00704          SMTPSenderRefused      The server didn't accept the from_addr.
00705          SMTPDataError          The server replied with an unexpected
00706                                 error code (other than a refusal of
00707                                 a recipient).
00708 
00709         Note: the connection will be open even after an exception is raised.
00710 
00711         Example:
00712 
00713          >>> import smtplib
00714          >>> s=smtplib.SMTP("localhost")
00715          >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
00716          >>> msg = '''\\
00717          ... From: Me@my.org
00718          ... Subject: testin'...
00719          ...
00720          ... This is a test '''
00721          >>> s.sendmail("me@my.org",tolist,msg)
00722          { "three@three.org" : ( 550 ,"User unknown" ) }
00723          >>> s.quit()
00724 
00725         In the above example, the message was accepted for delivery to three
00726         of the four addresses, and one was rejected, with the error code
00727         550.  If all addresses are accepted, then the method will return an
00728         empty dictionary.
00729 
00730         """
00731         self.ehlo_or_helo_if_needed()
00732         esmtp_opts = []
00733         if isinstance(msg, str):
00734             msg = _fix_eols(msg).encode('ascii')
00735         if self.does_esmtp:
00736             # Hmmm? what's this? -ddm
00737             # self.esmtp_features['7bit']=""
00738             if self.has_extn('size'):
00739                 esmtp_opts.append("size=%d" % len(msg))
00740             for option in mail_options:
00741                 esmtp_opts.append(option)
00742         (code, resp) = self.mail(from_addr, esmtp_opts)
00743         if code != 250:
00744             self.rset()
00745             raise SMTPSenderRefused(code, resp, from_addr)
00746         senderrs = {}
00747         if isinstance(to_addrs, str):
00748             to_addrs = [to_addrs]
00749         for each in to_addrs:
00750             (code, resp) = self.rcpt(each, rcpt_options)
00751             if (code != 250) and (code != 251):
00752                 senderrs[each] = (code, resp)
00753         if len(senderrs) == len(to_addrs):
00754             # the server refused all our recipients
00755             self.rset()
00756             raise SMTPRecipientsRefused(senderrs)
00757         (code, resp) = self.data(msg)
00758         if code != 250:
00759             self.rset()
00760             raise SMTPDataError(code, resp)
00761         #if we got here then somebody got our mail
00762         return senderrs

Here is the call graph for this function:

Here is the caller graph for this function:

def smtplib.SMTP.set_debuglevel (   self,
  debuglevel 
) [inherited]
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 280 of file smtplib.py.

00280 
00281     def set_debuglevel(self, debuglevel):
00282         """Set the debug output level.
00283 
00284         A non-false value results in debug messages for connection and for all
00285         messages sent to and received from the server.
00286 
00287         """
00288         self.debuglevel = debuglevel

def smtplib.SMTP.starttls (   self,
  keyfile = None,
  certfile = None 
) [inherited]
Puts the connection to the SMTP server into TLS mode.

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

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.

This method may raise the following exceptions:

 SMTPHeloError            The server didn't reply properly to
                  the helo greeting.

Definition at line 633 of file smtplib.py.

00633 
00634     def starttls(self, keyfile=None, certfile=None):
00635         """Puts the connection to the SMTP server into TLS mode.
00636 
00637         If there has been no previous EHLO or HELO command this session, this
00638         method tries ESMTP EHLO first.
00639 
00640         If the server supports TLS, this will encrypt the rest of the SMTP
00641         session. If you provide the keyfile and certfile parameters,
00642         the identity of the SMTP server and client can be checked. This,
00643         however, depends on whether the socket module really checks the
00644         certificates.
00645 
00646         This method may raise the following exceptions:
00647 
00648          SMTPHeloError            The server didn't reply properly to
00649                                   the helo greeting.
00650         """
00651         self.ehlo_or_helo_if_needed()
00652         if not self.has_extn("starttls"):
00653             raise SMTPException("STARTTLS extension not supported by server.")
00654         (resp, reply) = self.docmd("STARTTLS")
00655         if resp == 220:
00656             if not _have_ssl:
00657                 raise RuntimeError("No SSL support included in this Python")
00658             self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
00659             self.file = SSLFakeFile(self.sock)
00660             # RFC 3207:
00661             # The client MUST discard any knowledge obtained from
00662             # the server, such as the list of SMTP service extensions,
00663             # which was not obtained from the TLS negotiation itself.
00664             self.helo_resp = None
00665             self.ehlo_resp = None
00666             self.esmtp_features = {}
00667             self.does_esmtp = 0
00668         return (resp, reply)

Here is the call graph for this function:

def smtplib.SMTP.verify (   self,
  address 
) [inherited]
SMTP 'verify' command -- checks for address validity.

Definition at line 522 of file smtplib.py.

00522 
00523     def verify(self, address):
00524         """SMTP 'verify' command -- checks for address validity."""
00525         self.putcmd("vrfy", _addr_only(address))
        return self.getreply()

Here is the call graph for this function:


Member Data Documentation

Definition at line 847 of file smtplib.py.

int smtplib.SMTP.debuglevel = 0 [static, inherited]

Definition at line 236 of file smtplib.py.

Definition at line 287 of file smtplib.py.

Reimplemented from smtplib.SMTP.

Definition at line 841 of file smtplib.py.

int smtplib.SMTP.does_esmtp = 0 [static, inherited]

Definition at line 241 of file smtplib.py.

Definition at line 425 of file smtplib.py.

string smtplib.SMTP.ehlo_msg = "ehlo" [static, inherited]

Reimplemented in smtplib.LMTP.

Definition at line 239 of file smtplib.py.

smtplib.SMTP.ehlo_resp = None [static, inherited]

Definition at line 240 of file smtplib.py.

Definition at line 257 of file smtplib.py.

Reimplemented from smtplib.SMTP.

Definition at line 855 of file smtplib.py.

smtplib.SMTP.helo_resp = None [static, inherited]

Definition at line 238 of file smtplib.py.

Definition at line 846 of file smtplib.py.

Definition at line 263 of file smtplib.py.

smtplib.SMTP.sock [inherited]

Reimplemented in smtplib.LMTP.

Definition at line 319 of file smtplib.py.

smtplib.SMTP.timeout [inherited]

Definition at line 256 of file smtplib.py.

smtplib.SMTP.vrfy = verify [static, inherited]

Definition at line 527 of file smtplib.py.


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