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