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