blob: f6ac123823b69dddfd14a65b052cb2bbc5664371 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`smtplib` --- SMTP protocol client
2=======================================
3
4.. module:: smtplib
5 :synopsis: SMTP protocol client (requires sockets).
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
8
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009**Source code:** :source:`Lib/smtplib.py`
Georg Brandl116aa622007-08-15 14:28:22 +000010
11.. index::
12 pair: SMTP; protocol
13 single: Simple Mail Transfer Protocol
14
Raymond Hettinger469271d2011-01-27 20:38:46 +000015--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +000017The :mod:`smtplib` module defines an SMTP client session object that can be used
18to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For
19details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
20Protocol) and :rfc:`1869` (SMTP Service Extensions).
21
22
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080023.. class:: SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000024
Martin Panter7462b6492015-11-02 03:37:02 +000025 An :class:`SMTP` instance encapsulates an SMTP connection. It has methods
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000026 that support a full repertoire of SMTP and ESMTP operations. If the optional
R David Murray021362d2013-06-23 16:05:44 -040027 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
R David Murray6ceca4e2014-06-09 16:41:06 -040035 setting will be used). If the timeout expires, :exc:`socket.timeout` is
Martin Panterc04fb562016-02-10 05:44:01 +000036 raised. The optional source_address parameter allows binding
R David Murray021362d2013-06-23 16:05:44 -040037 to some specific source address in a machine with multiple network
38 interfaces, and/or to some specific source TCP port. It takes a 2-tuple
39 (host, port), for the socket to bind to as its source address before
40 connecting. If omitted (or if host or port are ``''`` and/or 0 respectively)
41 the OS default behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 For normal use, you should only require the initialization/connect,
takeyba579632018-11-24 01:53:24 +090044 :meth:`sendmail`, and :meth:`SMTP.quit` methods.
Jesus Ceac73f8632012-12-26 16:47:03 +010045 An example is included below.
Georg Brandl116aa622007-08-15 14:28:22 +000046
Barry Warsaw1f5c9582011-03-15 15:04:44 -040047 The :class:`SMTP` class supports the :keyword:`with` statement. When used
48 like this, the SMTP ``QUIT`` command is issued automatically when the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020049 :keyword:`!with` statement exits. E.g.::
Barry Warsaw1f5c9582011-03-15 15:04:44 -040050
51 >>> from smtplib import SMTP
52 >>> with SMTP("domain.org") as smtp:
53 ... smtp.noop()
54 ...
55 (250, b'Ok')
56 >>>
57
Steve Dower44f91c32019-06-27 10:47:59 -070058 .. audit-event:: smtplib.send self,data smtplib.SMTP
59
60 All commands will raise an :ref:`auditing event <auditing>`
61 ``smtplib.SMTP.send`` with arguments ``self`` and ``data``,
62 where ``data`` is the bytes about to be sent to the remote host.
Steve Dower60419a72019-06-24 08:42:54 -070063
Antoine Pitrou45456a02011-04-26 18:53:42 +020064 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040065 Support for the :keyword:`with` statement was added.
66
Senthil Kumaranb351a482011-07-31 09:14:17 +080067 .. versionchanged:: 3.3
68 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000069
R David Murraycee7cf62015-05-16 13:58:14 -040070 .. versionadded:: 3.5
71 The SMTPUTF8 extension (:rfc:`6531`) is now supported.
72
Dong-hee Na62e39732020-01-14 16:49:59 +090073 .. versionchanged:: 3.9
74 If the *timeout* parameter is set to be zero, it will raise a
75 :class:`ValueError` to prevent the creation of a non-blocking socket
R David Murraycee7cf62015-05-16 13:58:14 -040076
R David Murray36beb662013-06-23 15:47:50 -040077.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \
78 certfile=None [, timeout], context=None, \
79 source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000080
Martin Panter7462b6492015-11-02 03:37:02 +000081 An :class:`SMTP_SSL` instance behaves exactly the same as instances of
Georg Brandl116aa622007-08-15 14:28:22 +000082 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000083 required from the beginning of the connection and using :meth:`starttls` is
84 not appropriate. If *host* is not specified, the local host is used. If
R David Murray36beb662013-06-23 15:47:50 -040085 *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010086 arguments *local_hostname*, *timeout* and *source_address* have the same
87 meaning as they do in the :class:`SMTP` class. *context*, also optional,
Martin Panterc04fb562016-02-10 05:44:01 +000088 can contain a :class:`~ssl.SSLContext` and allows configuring various
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010089 aspects of the secure connection. Please read :ref:`ssl-security` for
90 best practices.
91
92 *keyfile* and *certfile* are a legacy alternative to *context*, and can
93 point to a PEM formatted private key and certificate chain file for the
94 SSL connection.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Antoine Pitroue0650202011-05-18 18:03:09 +020096 .. versionchanged:: 3.3
97 *context* was added.
98
Senthil Kumaranb351a482011-07-31 09:14:17 +080099 .. versionchanged:: 3.3
100 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Christian Heimesa5768f72013-12-02 20:44:17 +0100102 .. versionchanged:: 3.4
103 The class now supports hostname check with
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100104 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
105 :data:`ssl.HAS_SNI`).
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800106
Christian Heimesd0486372016-09-10 23:23:33 +0200107 .. deprecated:: 3.6
108
109 *keyfile* and *certfile* are deprecated in favor of *context*.
110 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
111 :func:`ssl.create_default_context` select the system's trusted CA
112 certificates for you.
113
Dong-hee Na62e39732020-01-14 16:49:59 +0900114 .. versionchanged:: 3.9
115 If the *timeout* parameter is set to be zero, it will raise a
116 :class:`ValueError` to prevent the creation of a non-blocking socket
Christian Heimesd0486372016-09-10 23:23:33 +0200117
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800118.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800121 standard SMTP client. It's common to use Unix sockets for LMTP, so our
122 :meth:`connect` method must support that as well as a regular host:port
Senthil Kumaranb351a482011-07-31 09:14:17 +0800123 server. The optional arguments local_hostname and source_address have the
R David Murray021362d2013-06-23 16:05:44 -0400124 same meaning as they do in the :class:`SMTP` class. To specify a Unix
125 socket, you must use an absolute path for *host*, starting with a '/'.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
R David Murray021362d2013-06-23 16:05:44 -0400127 Authentication is supported, using the regular SMTP mechanism. When using a
128 Unix socket, LMTP generally don't support or require any authentication, but
129 your mileage might vary.
Georg Brandl116aa622007-08-15 14:28:22 +0000130
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132A nice selection of exceptions is defined as well:
133
134
135.. exception:: SMTPException
136
R David Murray8a345962013-04-14 06:46:35 -0400137 Subclass of :exc:`OSError` that is the base exception class for all
Ned Deily7cf5e612013-08-13 01:15:14 -0700138 the other exceptions provided by this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Larry Hastings3732ed22014-03-15 21:13:56 -0700140 .. versionchanged:: 3.4
141 SMTPException became subclass of :exc:`OSError`
142
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144.. exception:: SMTPServerDisconnected
145
146 This exception is raised when the server unexpectedly disconnects, or when an
147 attempt is made to use the :class:`SMTP` instance before connecting it to a
148 server.
149
150
151.. exception:: SMTPResponseException
152
153 Base class for all exceptions that include an SMTP error code. These exceptions
154 are generated in some instances when the SMTP server returns an error code. The
155 error code is stored in the :attr:`smtp_code` attribute of the error, and the
156 :attr:`smtp_error` attribute is set to the error message.
157
158
159.. exception:: SMTPSenderRefused
160
161 Sender address refused. In addition to the attributes set by on all
162 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
163 the SMTP server refused.
164
165
166.. exception:: SMTPRecipientsRefused
167
168 All recipient addresses refused. The errors for each recipient are accessible
169 through the attribute :attr:`recipients`, which is a dictionary of exactly the
170 same sort as :meth:`SMTP.sendmail` returns.
171
172
173.. exception:: SMTPDataError
174
175 The SMTP server refused to accept the message data.
176
177
178.. exception:: SMTPConnectError
179
180 Error occurred during establishment of a connection with the server.
181
182
183.. exception:: SMTPHeloError
184
185 The server refused our ``HELO`` message.
186
187
R David Murraycee7cf62015-05-16 13:58:14 -0400188.. exception:: SMTPNotSupportedError
189
190 The command or option attempted is not supported by the server.
191
192 .. versionadded:: 3.5
193
194
Georg Brandl116aa622007-08-15 14:28:22 +0000195.. exception:: SMTPAuthenticationError
196
197 SMTP authentication went wrong. Most probably the server didn't accept the
198 username/password combination provided.
199
200
201.. seealso::
202
203 :rfc:`821` - Simple Mail Transfer Protocol
204 Protocol definition for SMTP. This document covers the model, operating
205 procedure, and protocol details for SMTP.
206
207 :rfc:`1869` - SMTP Service Extensions
208 Definition of the ESMTP extensions for SMTP. This describes a framework for
209 extending SMTP with new commands, supporting dynamic discovery of the commands
210 provided by the server, and defines a few additional commands.
211
212
213.. _smtp-objects:
214
215SMTP Objects
216------------
217
218An :class:`SMTP` instance has the following methods:
219
220
221.. method:: SMTP.set_debuglevel(level)
222
R David Murray2e6ad422015-04-16 17:24:52 -0400223 Set the debug output level. A value of 1 or ``True`` for *level* results in
224 debug messages for connection and for all messages sent to and received from
225 the server. A value of 2 for *level* results in these messages being
226 timestamped.
227
228 .. versionchanged:: 3.5 Added debuglevel 2.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230
Georg Brandl18244152009-09-02 20:34:52 +0000231.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Georg Brandl18244152009-09-02 20:34:52 +0000233 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000234 concatenated to the command, separated by a space.
235
236 This returns a 2-tuple composed of a numeric response code and the actual
237 response line (multiline responses are joined into one long line.)
238
239 In normal operation it should not be necessary to call this method explicitly.
240 It is used to implement other methods and may be useful for testing private
241 extensions.
242
243 If the connection to the server is lost while waiting for the reply,
244 :exc:`SMTPServerDisconnected` will be raised.
245
246
R David Murray14ee3cf2013-04-13 14:40:33 -0400247.. method:: SMTP.connect(host='localhost', port=0)
248
249 Connect to a host on a given port. The defaults are to connect to the local
250 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
251 followed by a number, that suffix will be stripped off and the number
252 interpreted as the port number to use. This method is automatically invoked by
253 the constructor if a host is specified during instantiation. Returns a
254 2-tuple of the response code and message sent by the server in its
255 connection response.
256
Steve Dower44f91c32019-06-27 10:47:59 -0700257 .. audit-event:: smtplib.connect self,host,port smtplib.SMTP.connect
Steve Dower60419a72019-06-24 08:42:54 -0700258
R David Murray14ee3cf2013-04-13 14:40:33 -0400259
Georg Brandl18244152009-09-02 20:34:52 +0000260.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262 Identify yourself to the SMTP server using ``HELO``. The hostname argument
263 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000264 The message returned by the server is stored as the :attr:`helo_resp` attribute
265 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 In normal operation it should not be necessary to call this method explicitly.
268 It will be implicitly called by the :meth:`sendmail` when necessary.
269
270
Georg Brandl18244152009-09-02 20:34:52 +0000271.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
274 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000275 response for ESMTP option and store them for use by :meth:`has_extn`.
276 Also sets several informational attributes: the message returned by
277 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000278 is set to true or false depending on whether the server supports ESMTP, and
279 :attr:`esmtp_features` will be a dictionary containing the names of the
R David Murray76e13c12014-07-03 14:47:46 -0400280 SMTP service extensions this server supports, and their parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
283 necessary to call this method explicitly. It will be implicitly called by
284 :meth:`sendmail` when necessary.
285
Christian Heimes679db4a2008-01-18 09:56:22 +0000286.. method:: SMTP.ehlo_or_helo_if_needed()
287
Ville Skyttäda120632018-08-13 06:39:19 +0300288 This method calls :meth:`ehlo` and/or :meth:`helo` if there has been no
Christian Heimes679db4a2008-01-18 09:56:22 +0000289 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
290 first.
291
Georg Brandl1f01deb2009-01-03 22:47:39 +0000292 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000293 The server didn't reply properly to the ``HELO`` greeting.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295.. method:: SMTP.has_extn(name)
296
297 Return :const:`True` if *name* is in the set of SMTP service extensions returned
298 by the server, :const:`False` otherwise. Case is ignored.
299
300
301.. method:: SMTP.verify(address)
302
303 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
304 tuple consisting of code 250 and a full :rfc:`822` address (including human
305 name) if the user address is valid. Otherwise returns an SMTP error code of 400
306 or greater and an error string.
307
308 .. note::
309
310 Many sites disable SMTP ``VRFY`` in order to foil spammers.
311
312
Barry Warsawc5ea7542015-07-09 10:39:55 -0400313.. method:: SMTP.login(user, password, *, initial_response_ok=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315 Log in on an SMTP server that requires authentication. The arguments are the
316 username and the password to authenticate with. If there has been no previous
317 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
318 first. This method will return normally if the authentication was successful, or
319 may raise the following exceptions:
320
321 :exc:`SMTPHeloError`
322 The server didn't reply properly to the ``HELO`` greeting.
323
324 :exc:`SMTPAuthenticationError`
325 The server didn't accept the username/password combination.
326
R David Murraycee7cf62015-05-16 13:58:14 -0400327 :exc:`SMTPNotSupportedError`
328 The ``AUTH`` command is not supported by the server.
329
Georg Brandl116aa622007-08-15 14:28:22 +0000330 :exc:`SMTPException`
331 No suitable authentication method was found.
332
R David Murray76e13c12014-07-03 14:47:46 -0400333 Each of the authentication methods supported by :mod:`smtplib` are tried in
Barry Warsawc5ea7542015-07-09 10:39:55 -0400334 turn if they are advertised as supported by the server. See :meth:`auth`
335 for a list of supported authentication methods. *initial_response_ok* is
336 passed through to :meth:`auth`.
337
338 Optional keyword argument *initial_response_ok* specifies whether, for
339 authentication methods that support it, an "initial response" as specified
340 in :rfc:`4954` can be sent along with the ``AUTH`` command, rather than
341 requiring a challenge/response.
R David Murray76e13c12014-07-03 14:47:46 -0400342
R David Murraycee7cf62015-05-16 13:58:14 -0400343 .. versionchanged:: 3.5
Barry Warsawc5ea7542015-07-09 10:39:55 -0400344 :exc:`SMTPNotSupportedError` may be raised, and the
345 *initial_response_ok* parameter was added.
R David Murraycee7cf62015-05-16 13:58:14 -0400346
R David Murray76e13c12014-07-03 14:47:46 -0400347
Barry Warsawc5ea7542015-07-09 10:39:55 -0400348.. method:: SMTP.auth(mechanism, authobject, *, initial_response_ok=True)
R David Murray76e13c12014-07-03 14:47:46 -0400349
350 Issue an ``SMTP`` ``AUTH`` command for the specified authentication
351 *mechanism*, and handle the challenge response via *authobject*.
352
353 *mechanism* specifies which authentication mechanism is to
354 be used as argument to the ``AUTH`` command; the valid values are
355 those listed in the ``auth`` element of :attr:`esmtp_features`.
356
Barry Warsawc5ea7542015-07-09 10:39:55 -0400357 *authobject* must be a callable object taking an optional single argument:
R David Murray76e13c12014-07-03 14:47:46 -0400358
Barry Warsawc5ea7542015-07-09 10:39:55 -0400359 data = authobject(challenge=None)
R David Murray76e13c12014-07-03 14:47:46 -0400360
Barry Warsawc5ea7542015-07-09 10:39:55 -0400361 If optional keyword argument *initial_response_ok* is true,
362 ``authobject()`` will be called first with no argument. It can return the
Sebastian Rittau78deb7f2018-09-10 19:29:43 +0200363 :rfc:`4954` "initial response" ASCII ``str`` which will be encoded and sent with
Barry Warsawc5ea7542015-07-09 10:39:55 -0400364 the ``AUTH`` command as below. If the ``authobject()`` does not support an
365 initial response (e.g. because it requires a challenge), it should return
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300366 ``None`` when called with ``challenge=None``. If *initial_response_ok* is
367 false, then ``authobject()`` will not be called first with ``None``.
Barry Warsawc5ea7542015-07-09 10:39:55 -0400368
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300369 If the initial response check returns ``None``, or if *initial_response_ok* is
Barry Warsawc5ea7542015-07-09 10:39:55 -0400370 false, ``authobject()`` will be called to process the server's challenge
371 response; the *challenge* argument it is passed will be a ``bytes``. It
Sebastian Rittau78deb7f2018-09-10 19:29:43 +0200372 should return ASCII ``str`` *data* that will be base64 encoded and sent to the
Barry Warsawc5ea7542015-07-09 10:39:55 -0400373 server.
R David Murray76e13c12014-07-03 14:47:46 -0400374
375 The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``,
376 and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``,
377 ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively. They all require
378 that the ``user`` and ``password`` properties of the ``SMTP`` instance are
379 set to appropriate values.
380
381 User code does not normally need to call ``auth`` directly, but can instead
Barry Warsawc5ea7542015-07-09 10:39:55 -0400382 call the :meth:`login` method, which will try each of the above mechanisms
383 in turn, in the order listed. ``auth`` is exposed to facilitate the
384 implementation of authentication methods not (or not yet) supported
385 directly by :mod:`smtplib`.
R David Murray76e13c12014-07-03 14:47:46 -0400386
387 .. versionadded:: 3.5
388
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Antoine Pitroue0650202011-05-18 18:03:09 +0200390.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
393 commands that follow will be encrypted. You should then call :meth:`ehlo`
394 again.
395
Ville Skyttäda120632018-08-13 06:39:19 +0300396 If *keyfile* and *certfile* are provided, they are used to create an
397 :class:`ssl.SSLContext`.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Ville Skyttäda120632018-08-13 06:39:19 +0300399 Optional *context* parameter is an :class:`ssl.SSLContext` object; This is
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300400 an alternative to using a keyfile and a certfile and if specified both
401 *keyfile* and *certfile* should be ``None``.
Antoine Pitroue0650202011-05-18 18:03:09 +0200402
Christian Heimes679db4a2008-01-18 09:56:22 +0000403 If there has been no previous ``EHLO`` or ``HELO`` command this session,
404 this method tries ESMTP ``EHLO`` first.
405
Ville Skyttäda120632018-08-13 06:39:19 +0300406 .. deprecated:: 3.6
407
408 *keyfile* and *certfile* are deprecated in favor of *context*.
409 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
410 :func:`ssl.create_default_context` select the system's trusted CA
411 certificates for you.
412
Christian Heimes679db4a2008-01-18 09:56:22 +0000413 :exc:`SMTPHeloError`
414 The server didn't reply properly to the ``HELO`` greeting.
415
R David Murraycee7cf62015-05-16 13:58:14 -0400416 :exc:`SMTPNotSupportedError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000417 The server does not support the STARTTLS extension.
418
Christian Heimes679db4a2008-01-18 09:56:22 +0000419 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000420 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000421
Antoine Pitroue0650202011-05-18 18:03:09 +0200422 .. versionchanged:: 3.3
423 *context* was added.
424
Christian Heimesa5768f72013-12-02 20:44:17 +0100425 .. versionchanged:: 3.4
426 The method now supports hostname check with
427 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
428 :data:`~ssl.HAS_SNI`).
429
R David Murraycee7cf62015-05-16 13:58:14 -0400430 .. versionchanged:: 3.5
431 The error raised for lack of STARTTLS support is now the
432 :exc:`SMTPNotSupportedError` subclass instead of the base
433 :exc:`SMTPException`.
434
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200436.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438 Send mail. The required arguments are an :rfc:`822` from-address string, a list
439 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
440 address), and a message string. The caller may pass a list of ESMTP options
441 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
442 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
443 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
444 options to different recipients you have to use the low-level methods such as
445 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
446
447 .. note::
448
449 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000450 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000451 message headers in any way.
452
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600453 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000454 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600455 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
456 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000457
Georg Brandl116aa622007-08-15 14:28:22 +0000458 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
459 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
460 each of the specified options will be passed to it (if the option is in the
461 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
462 and ESMTP options suppressed.
463
464 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000465 recipient. Otherwise it will raise an exception. That is, if this method does
466 not raise an exception, then someone should get your mail. If this method does
467 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000468 recipient that was refused. Each entry contains a tuple of the SMTP error code
469 and the accompanying error message sent by the server.
470
R David Murraycee7cf62015-05-16 13:58:14 -0400471 If ``SMTPUTF8`` is included in *mail_options*, and the server supports it,
Raymond Hettinger624e2222016-08-30 13:25:06 -0700472 *from_addr* and *to_addrs* may contain non-ASCII characters.
R David Murraycee7cf62015-05-16 13:58:14 -0400473
Georg Brandl116aa622007-08-15 14:28:22 +0000474 This method may raise the following exceptions:
475
476 :exc:`SMTPRecipientsRefused`
477 All recipients were refused. Nobody got the mail. The :attr:`recipients`
478 attribute of the exception object is a dictionary with information about the
479 refused recipients (like the one returned when at least one recipient was
480 accepted).
481
482 :exc:`SMTPHeloError`
483 The server didn't reply properly to the ``HELO`` greeting.
484
485 :exc:`SMTPSenderRefused`
486 The server didn't accept the *from_addr*.
487
488 :exc:`SMTPDataError`
489 The server replied with an unexpected error code (other than a refusal of a
490 recipient).
491
R David Murraycee7cf62015-05-16 13:58:14 -0400492 :exc:`SMTPNotSupportedError`
493 ``SMTPUTF8`` was given in the *mail_options* but is not supported by the
494 server.
495
Georg Brandl116aa622007-08-15 14:28:22 +0000496 Unless otherwise noted, the connection will be open even after an exception is
497 raised.
498
Georg Brandl61063cc2012-06-24 22:48:30 +0200499 .. versionchanged:: 3.2
500 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000501
R David Murraycee7cf62015-05-16 13:58:14 -0400502 .. versionchanged:: 3.5
503 ``SMTPUTF8`` support added, and :exc:`SMTPNotSupportedError` may be
504 raised if ``SMTPUTF8`` is specified but the server does not support it.
505
R. David Murray7dff9e02010-11-08 17:15:13 +0000506
R David Murrayac4e5ab2011-07-02 21:03:19 -0400507.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200508 mail_options=(), rcpt_options=())
R. David Murray7dff9e02010-11-08 17:15:13 +0000509
510 This is a convenience method for calling :meth:`sendmail` with the message
511 represented by an :class:`email.message.Message` object. The arguments have
512 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
513 object.
514
R David Murrayac4e5ab2011-07-02 21:03:19 -0400515 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
516 those arguments with addresses extracted from the headers of *msg* as
R David Murray83084442015-05-17 19:27:22 -0400517 specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender`
R David Murrayac4e5ab2011-07-02 21:03:19 -0400518 field if it is present, and otherwise to the :mailheader:`From` field.
Raymond Hettinger624e2222016-08-30 13:25:06 -0700519 *to_addrs* combines the values (if any) of the :mailheader:`To`,
R David Murrayac4e5ab2011-07-02 21:03:19 -0400520 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
521 set of :mailheader:`Resent-*` headers appear in the message, the regular
522 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
523 If the message contains more than one set of :mailheader:`Resent-*` headers,
524 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
525 the most recent set of :mailheader:`Resent-` headers.
526
527 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000528 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400529 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
530 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
531 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
R David Murray83084442015-05-17 19:27:22 -0400532 in *msg*. If any of the addresses in *from_addr* and *to_addrs* contain
533 non-ASCII characters and the server does not advertise ``SMTPUTF8`` support,
534 an :exc:`SMTPNotSupported` error is raised. Otherwise the ``Message`` is
535 serialized with a clone of its :mod:`~email.policy` with the
536 :attr:`~email.policy.EmailPolicy.utf8` attribute set to ``True``, and
537 ``SMTPUTF8`` and ``BODY=8BITMIME`` are added to *mail_options*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000538
539 .. versionadded:: 3.2
540
R David Murray83084442015-05-17 19:27:22 -0400541 .. versionadded:: 3.5
542 Support for internationalized addresses (``SMTPUTF8``).
543
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545.. method:: SMTP.quit()
546
Christian Heimesba4af492008-03-28 00:55:15 +0000547 Terminate the SMTP session and close the connection. Return the result of
548 the SMTP ``QUIT`` command.
549
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
552``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
553Normally these do not need to be called directly, so they are not documented
554here. For details, consult the module code.
555
556
557.. _smtp-example:
558
559SMTP Example
560------------
561
562This example prompts the user for addresses needed in the message envelope ('To'
563and 'From' addresses), and the message to be delivered. Note that the headers
564to be included with the message must be included in the message as entered; this
565example doesn't do any processing of the :rfc:`822` headers. In particular, the
566'To' and 'From' addresses must be included in the message headers explicitly. ::
567
568 import smtplib
569
Georg Brandl116aa622007-08-15 14:28:22 +0000570 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000571 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000572
573 fromaddr = prompt("From: ")
574 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000575 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577 # Add the From: and To: headers at the start!
578 msg = ("From: %s\r\nTo: %s\r\n\r\n"
579 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000580 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000581 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000582 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000583 except EOFError:
584 break
585 if not line:
586 break
587 msg = msg + line
588
Georg Brandl6911e3c2007-09-04 07:15:32 +0000589 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591 server = smtplib.SMTP('localhost')
592 server.set_debuglevel(1)
593 server.sendmail(fromaddr, toaddrs, msg)
594 server.quit()
595
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000596.. note::
597
598 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000599 construct an email message, which you can then send
600 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.