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