Home | History | Annotate | Download | only in library
      1 :mod:`smtplib` --- SMTP protocol client
      2 =======================================
      3 
      4 .. module:: smtplib
      5    :synopsis: SMTP protocol client (requires sockets).
      6 .. sectionauthor:: Eric S. Raymond <esr (a] snark.thyrsus.com>
      7 
      8 
      9 .. index::
     10    pair: SMTP; protocol
     11    single: Simple Mail Transfer Protocol
     12 
     13 **Source code:** :source:`Lib/smtplib.py`
     14 
     15 --------------
     16 
     17 The :mod:`smtplib` module defines an SMTP client session object that can be used
     18 to send mail to any Internet machine with an SMTP or ESMTP listener daemon.  For
     19 details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
     20 Protocol) and :rfc:`1869` (SMTP Service Extensions).
     21 
     22 
     23 .. class:: SMTP([host[, port[, local_hostname[, timeout]]]])
     24 
     25    An :class:`SMTP` instance encapsulates an SMTP connection.  It has methods
     26    that support a full repertoire of SMTP and ESMTP operations. If the optional
     27    host and port parameters are given, the SMTP :meth:`connect` method is
     28    called with those parameters during initialization.  If specified,
     29    *local_hostname* is used as the FQDN of the local host in the HELO/EHLO
     30    command.  Otherwise, the local hostname is found using
     31    :func:`socket.getfqdn`.  If the :meth:`connect` call returns anything other
     32    than a success code, an :exc:`SMTPConnectError` is raised. The optional
     33    *timeout* parameter specifies a timeout in seconds for blocking operations
     34    like the connection attempt (if not specified, the global default timeout
     35    setting will be used).  If the timeout expires, :exc:`socket.timeout`
     36    is raised.
     37 
     38    For normal use, you should only require the initialization/connect,
     39    :meth:`sendmail`, and :meth:`~smtplib.quit` methods.
     40    An example is included below.
     41 
     42    .. versionchanged:: 2.6
     43       *timeout* was added.
     44 
     45 
     46 .. class:: SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])
     47 
     48    An :class:`SMTP_SSL` instance behaves exactly the same as instances of
     49    :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
     50    required from the beginning of the connection and using :meth:`starttls` is
     51    not appropriate. If *host* is not specified, the local host is used. If
     52    *port* is omitted, the standard SMTP-over-SSL port (465) is used.
     53    *local_hostname* has the same meaning as it does for the :class:`SMTP`
     54    class.  *keyfile* and *certfile* are also optional, and can contain a PEM
     55    formatted private key and certificate chain file for the SSL connection. The
     56    optional *timeout* parameter specifies a timeout in seconds for blocking
     57    operations like the connection attempt (if not specified, the global default
     58    timeout setting will be used).  If the timeout expires, :exc:`socket.timeout`
     59    is raised.
     60 
     61    .. versionadded:: 2.6
     62 
     63 
     64 .. class:: LMTP([host[, port[, local_hostname]]])
     65 
     66    The LMTP protocol, which is very similar to ESMTP, is heavily based on the
     67    standard SMTP client. It's common to use Unix sockets for LMTP, so our
     68    :meth:`connect` method must support that as well as a regular host:port
     69    server.  *local_hostname* has the same meaning as it does for the
     70    :class:`SMTP` class.  To specify a Unix socket, you must use an absolute
     71    path for *host*, starting with a '/'.
     72 
     73    Authentication is supported, using the regular SMTP mechanism. When using a
     74    Unix socket, LMTP generally don't support or require any authentication, but
     75    your mileage might vary.
     76 
     77    .. versionadded:: 2.6
     78 
     79 A nice selection of exceptions is defined as well:
     80 
     81 
     82 .. exception:: SMTPException
     83 
     84    The base exception class for all the other exceptions provided by this
     85    module.
     86 
     87 
     88 .. exception:: SMTPServerDisconnected
     89 
     90    This exception is raised when the server unexpectedly disconnects, or when an
     91    attempt is made to use the :class:`SMTP` instance before connecting it to a
     92    server.
     93 
     94 
     95 .. exception:: SMTPResponseException
     96 
     97    Base class for all exceptions that include an SMTP error code. These exceptions
     98    are generated in some instances when the SMTP server returns an error code.  The
     99    error code is stored in the :attr:`smtp_code` attribute of the error, and the
    100    :attr:`smtp_error` attribute is set to the error message.
    101 
    102 
    103 .. exception:: SMTPSenderRefused
    104 
    105    Sender address refused.  In addition to the attributes set by on all
    106    :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
    107    the SMTP server refused.
    108 
    109 
    110 .. exception:: SMTPRecipientsRefused
    111 
    112    All recipient addresses refused.  The errors for each recipient are accessible
    113    through the attribute :attr:`recipients`, which is a dictionary of exactly the
    114    same sort as :meth:`SMTP.sendmail` returns.
    115 
    116 
    117 .. exception:: SMTPDataError
    118 
    119    The SMTP server refused to accept the message data.
    120 
    121 
    122 .. exception:: SMTPConnectError
    123 
    124    Error occurred during establishment of a connection  with the server.
    125 
    126 
    127 .. exception:: SMTPHeloError
    128 
    129    The server refused our ``HELO`` message.
    130 
    131 
    132 .. exception:: SMTPAuthenticationError
    133 
    134    SMTP authentication went wrong.  Most probably the server didn't accept the
    135    username/password combination provided.
    136 
    137 
    138 .. seealso::
    139 
    140    :rfc:`821` - Simple Mail Transfer Protocol
    141       Protocol definition for SMTP.  This document covers the model, operating
    142       procedure, and protocol details for SMTP.
    143 
    144    :rfc:`1869` - SMTP Service Extensions
    145       Definition of the ESMTP extensions for SMTP.  This describes a framework for
    146       extending SMTP with new commands, supporting dynamic discovery of the commands
    147       provided by the server, and defines a few additional commands.
    148 
    149 
    150 .. _smtp-objects:
    151 
    152 SMTP Objects
    153 ------------
    154 
    155 An :class:`SMTP` instance has the following methods:
    156 
    157 
    158 .. method:: SMTP.set_debuglevel(level)
    159 
    160    Set the debug output level.  A true value for *level* results in debug messages
    161    for connection and for all messages sent to and received from the server.
    162 
    163 
    164 .. method:: SMTP.docmd(cmd, [, argstring])
    165 
    166    Send a command *cmd* to the server.  The optional argument *argstring* is simply
    167    concatenated to the command, separated by a space.
    168 
    169    This returns a 2-tuple composed of a numeric response code and the actual
    170    response line (multiline responses are joined into one long line.)
    171 
    172    In normal operation it should not be necessary to call this method explicitly.
    173    It is used to implement other methods and may be useful for testing private
    174    extensions.
    175 
    176    If the connection to the server is lost while waiting for the reply,
    177    :exc:`SMTPServerDisconnected` will be raised.
    178 
    179 
    180 .. method:: SMTP.connect([host[, port]])
    181 
    182    Connect to a host on a given port.  The defaults are to connect to the local
    183    host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
    184    followed by a number, that suffix will be stripped off and the number
    185    interpreted as the port number to use. This method is automatically invoked by
    186    the constructor if a host is specified during instantiation.  Returns a
    187    2-tuple of the response code and message sent by the server in its
    188    connection response.
    189 
    190 
    191 .. method:: SMTP.helo([hostname])
    192 
    193    Identify yourself to the SMTP server using ``HELO``.  The hostname argument
    194    defaults to the fully qualified domain name of the local host.
    195    The message returned by the server is stored as the :attr:`helo_resp` attribute
    196    of the object.
    197 
    198    In normal operation it should not be necessary to call this method explicitly.
    199    It will be implicitly called by the :meth:`sendmail` when necessary.
    200 
    201 
    202 .. method:: SMTP.ehlo([hostname])
    203 
    204    Identify yourself to an ESMTP server using ``EHLO``.  The hostname argument
    205    defaults to the fully qualified domain name of the local host.  Examine the
    206    response for ESMTP option and store them for use by :meth:`has_extn`.
    207    Also sets several informational attributes: the message returned by
    208    the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
    209    is set to true or false depending on whether the server supports ESMTP, and
    210    :attr:`esmtp_features` will be a dictionary containing the names of the
    211    SMTP service extensions this server supports, and their
    212    parameters (if any).
    213 
    214    Unless you wish to use :meth:`has_extn` before sending mail, it should not be
    215    necessary to call this method explicitly.  It will be implicitly called by
    216    :meth:`sendmail` when necessary.
    217 
    218 .. method:: SMTP.ehlo_or_helo_if_needed()
    219 
    220    This method call :meth:`ehlo` and or :meth:`helo` if there has been no
    221    previous ``EHLO`` or ``HELO`` command this session.  It tries ESMTP ``EHLO``
    222    first.
    223 
    224    :exc:`SMTPHeloError`
    225      The server didn't reply properly to the ``HELO`` greeting.
    226 
    227    .. versionadded:: 2.6
    228 
    229 .. method:: SMTP.has_extn(name)
    230 
    231    Return :const:`True` if *name* is in the set of SMTP service extensions returned
    232    by the server, :const:`False` otherwise. Case is ignored.
    233 
    234 
    235 .. method:: SMTP.verify(address)
    236 
    237    Check the validity of an address on this server using SMTP ``VRFY``. Returns a
    238    tuple consisting of code 250 and a full :rfc:`822` address (including human
    239    name) if the user address is valid. Otherwise returns an SMTP error code of 400
    240    or greater and an error string.
    241 
    242    .. note::
    243 
    244       Many sites disable SMTP ``VRFY`` in order to foil spammers.
    245 
    246 
    247 .. method:: SMTP.login(user, password)
    248 
    249    Log in on an SMTP server that requires authentication. The arguments are the
    250    username and the password to authenticate with. If there has been no previous
    251    ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
    252    first. This method will return normally if the authentication was successful, or
    253    may raise the following exceptions:
    254 
    255    :exc:`SMTPHeloError`
    256       The server didn't reply properly to the ``HELO`` greeting.
    257 
    258    :exc:`SMTPAuthenticationError`
    259       The server didn't accept the username/password combination.
    260 
    261    :exc:`SMTPException`
    262       No suitable authentication method was found.
    263 
    264 
    265 .. method:: SMTP.starttls([keyfile[, certfile]])
    266 
    267    Put the SMTP connection in TLS (Transport Layer Security) mode.  All SMTP
    268    commands that follow will be encrypted.  You should then call :meth:`ehlo`
    269    again.
    270 
    271    If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
    272    module's :func:`ssl` function.
    273 
    274    If there has been no previous ``EHLO`` or ``HELO`` command this session,
    275    this method tries ESMTP ``EHLO`` first.
    276 
    277    .. versionchanged:: 2.6
    278 
    279    :exc:`SMTPHeloError`
    280       The server didn't reply properly to the ``HELO`` greeting.
    281 
    282    :exc:`SMTPException`
    283      The server does not support the STARTTLS extension.
    284 
    285    .. versionchanged:: 2.6
    286 
    287    :exc:`RuntimeError`
    288      SSL/TLS support is not available to your Python interpreter.
    289 
    290 
    291 .. method:: SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
    292 
    293    Send mail.  The required arguments are an :rfc:`822` from-address string, a list
    294    of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
    295    address), and a message string.  The caller may pass a list of ESMTP options
    296    (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
    297    ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
    298    commands can be passed as *rcpt_options*.  (If you need to use different ESMTP
    299    options to different recipients you have to use the low-level methods such as
    300    :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
    301 
    302    .. note::
    303 
    304       The *from_addr* and *to_addrs* parameters are used to construct the message
    305       envelope used by the transport agents. The :class:`SMTP` does not modify the
    306       message headers in any way.
    307 
    308    If there has been no previous ``EHLO`` or ``HELO`` command this session, this
    309    method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
    310    each of the specified options will be passed to it (if the option is in the
    311    feature set the server advertises).  If ``EHLO`` fails, ``HELO`` will be tried
    312    and ESMTP options suppressed.
    313 
    314    This method will return normally if the mail is accepted for at least one
    315    recipient. Otherwise it will raise an exception.  That is, if this method does
    316    not raise an exception, then someone should get your mail. If this method does
    317    not raise an exception, it returns a dictionary, with one entry for each
    318    recipient that was refused.  Each entry contains a tuple of the SMTP error code
    319    and the accompanying error message sent by the server.
    320 
    321    This method may raise the following exceptions:
    322 
    323    :exc:`SMTPRecipientsRefused`
    324       All recipients were refused.  Nobody got the mail.  The :attr:`recipients`
    325       attribute of the exception object is a dictionary with information about the
    326       refused recipients (like the one returned when at least one recipient was
    327       accepted).
    328 
    329    :exc:`SMTPHeloError`
    330       The server didn't reply properly to the ``HELO`` greeting.
    331 
    332    :exc:`SMTPSenderRefused`
    333       The server didn't accept the *from_addr*.
    334 
    335    :exc:`SMTPDataError`
    336       The server replied with an unexpected error code (other than a refusal of a
    337       recipient).
    338 
    339    Unless otherwise noted, the connection will be open even after an exception is
    340    raised.
    341 
    342 
    343 .. method:: SMTP.quit()
    344 
    345    Terminate the SMTP session and close the connection.  Return the result of
    346    the SMTP ``QUIT`` command.
    347 
    348    .. versionchanged:: 2.6
    349       Return a value.
    350 
    351 
    352 Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
    353 ``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
    354 Normally these do not need to be called directly, so they are not documented
    355 here.  For details, consult the module code.
    356 
    357 
    358 .. _smtp-example:
    359 
    360 SMTP Example
    361 ------------
    362 
    363 This example prompts the user for addresses needed in the message envelope ('To'
    364 and 'From' addresses), and the message to be delivered.  Note that the headers
    365 to be included with the message must be included in the message as entered; this
    366 example doesn't do any processing of the :rfc:`822` headers.  In particular, the
    367 'To' and 'From' addresses must be included in the message headers explicitly. ::
    368 
    369    import smtplib
    370 
    371    def prompt(prompt):
    372        return raw_input(prompt).strip()
    373 
    374    fromaddr = prompt("From: ")
    375    toaddrs  = prompt("To: ").split()
    376    print "Enter message, end with ^D (Unix) or ^Z (Windows):"
    377 
    378    # Add the From: and To: headers at the start!
    379    msg = ("From: %s\r\nTo: %s\r\n\r\n"
    380           % (fromaddr, ", ".join(toaddrs)))
    381    while 1:
    382        try:
    383            line = raw_input()
    384        except EOFError:
    385            break
    386        if not line:
    387            break
    388        msg = msg + line
    389 
    390    print "Message length is " + repr(len(msg))
    391 
    392    server = smtplib.SMTP('localhost')
    393    server.set_debuglevel(1)
    394    server.sendmail(fromaddr, toaddrs, msg)
    395    server.quit()
    396 
    397 .. note::
    398 
    399    In general, you will want to use the :mod:`email` package's features to
    400    construct an email message, which you can then convert to a string and send
    401    via :meth:`sendmail`; see :ref:`email-examples`.
    402