blob: 6176c35a0e4a50d139845b8528577e75969a8828 [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
73
R David Murray36beb662013-06-23 15:47:50 -040074.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \
75 certfile=None [, timeout], context=None, \
76 source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000077
Martin Panter7462b6492015-11-02 03:37:02 +000078 An :class:`SMTP_SSL` instance behaves exactly the same as instances of
Georg Brandl116aa622007-08-15 14:28:22 +000079 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000080 required from the beginning of the connection and using :meth:`starttls` is
81 not appropriate. If *host* is not specified, the local host is used. If
R David Murray36beb662013-06-23 15:47:50 -040082 *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010083 arguments *local_hostname*, *timeout* and *source_address* have the same
84 meaning as they do in the :class:`SMTP` class. *context*, also optional,
Martin Panterc04fb562016-02-10 05:44:01 +000085 can contain a :class:`~ssl.SSLContext` and allows configuring various
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010086 aspects of the secure connection. Please read :ref:`ssl-security` for
87 best practices.
88
89 *keyfile* and *certfile* are a legacy alternative to *context*, and can
90 point to a PEM formatted private key and certificate chain file for the
91 SSL connection.
Georg Brandl116aa622007-08-15 14:28:22 +000092
Antoine Pitroue0650202011-05-18 18:03:09 +020093 .. versionchanged:: 3.3
94 *context* was added.
95
Senthil Kumaranb351a482011-07-31 09:14:17 +080096 .. versionchanged:: 3.3
97 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000098
Christian Heimesa5768f72013-12-02 20:44:17 +010099 .. versionchanged:: 3.4
100 The class now supports hostname check with
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100101 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
102 :data:`ssl.HAS_SNI`).
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800103
Christian Heimesd0486372016-09-10 23:23:33 +0200104 .. deprecated:: 3.6
105
106 *keyfile* and *certfile* are deprecated in favor of *context*.
107 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
108 :func:`ssl.create_default_context` select the system's trusted CA
109 certificates for you.
110
111
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800112.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800115 standard SMTP client. It's common to use Unix sockets for LMTP, so our
116 :meth:`connect` method must support that as well as a regular host:port
Senthil Kumaranb351a482011-07-31 09:14:17 +0800117 server. The optional arguments local_hostname and source_address have the
R David Murray021362d2013-06-23 16:05:44 -0400118 same meaning as they do in the :class:`SMTP` class. To specify a Unix
119 socket, you must use an absolute path for *host*, starting with a '/'.
Georg Brandl116aa622007-08-15 14:28:22 +0000120
R David Murray021362d2013-06-23 16:05:44 -0400121 Authentication is supported, using the regular SMTP mechanism. When using a
122 Unix socket, LMTP generally don't support or require any authentication, but
123 your mileage might vary.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126A nice selection of exceptions is defined as well:
127
128
129.. exception:: SMTPException
130
R David Murray8a345962013-04-14 06:46:35 -0400131 Subclass of :exc:`OSError` that is the base exception class for all
Ned Deily7cf5e612013-08-13 01:15:14 -0700132 the other exceptions provided by this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Larry Hastings3732ed22014-03-15 21:13:56 -0700134 .. versionchanged:: 3.4
135 SMTPException became subclass of :exc:`OSError`
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. exception:: SMTPServerDisconnected
139
140 This exception is raised when the server unexpectedly disconnects, or when an
141 attempt is made to use the :class:`SMTP` instance before connecting it to a
142 server.
143
144
145.. exception:: SMTPResponseException
146
147 Base class for all exceptions that include an SMTP error code. These exceptions
148 are generated in some instances when the SMTP server returns an error code. The
149 error code is stored in the :attr:`smtp_code` attribute of the error, and the
150 :attr:`smtp_error` attribute is set to the error message.
151
152
153.. exception:: SMTPSenderRefused
154
155 Sender address refused. In addition to the attributes set by on all
156 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
157 the SMTP server refused.
158
159
160.. exception:: SMTPRecipientsRefused
161
162 All recipient addresses refused. The errors for each recipient are accessible
163 through the attribute :attr:`recipients`, which is a dictionary of exactly the
164 same sort as :meth:`SMTP.sendmail` returns.
165
166
167.. exception:: SMTPDataError
168
169 The SMTP server refused to accept the message data.
170
171
172.. exception:: SMTPConnectError
173
174 Error occurred during establishment of a connection with the server.
175
176
177.. exception:: SMTPHeloError
178
179 The server refused our ``HELO`` message.
180
181
R David Murraycee7cf62015-05-16 13:58:14 -0400182.. exception:: SMTPNotSupportedError
183
184 The command or option attempted is not supported by the server.
185
186 .. versionadded:: 3.5
187
188
Georg Brandl116aa622007-08-15 14:28:22 +0000189.. exception:: SMTPAuthenticationError
190
191 SMTP authentication went wrong. Most probably the server didn't accept the
192 username/password combination provided.
193
194
195.. seealso::
196
197 :rfc:`821` - Simple Mail Transfer Protocol
198 Protocol definition for SMTP. This document covers the model, operating
199 procedure, and protocol details for SMTP.
200
201 :rfc:`1869` - SMTP Service Extensions
202 Definition of the ESMTP extensions for SMTP. This describes a framework for
203 extending SMTP with new commands, supporting dynamic discovery of the commands
204 provided by the server, and defines a few additional commands.
205
206
207.. _smtp-objects:
208
209SMTP Objects
210------------
211
212An :class:`SMTP` instance has the following methods:
213
214
215.. method:: SMTP.set_debuglevel(level)
216
R David Murray2e6ad422015-04-16 17:24:52 -0400217 Set the debug output level. A value of 1 or ``True`` for *level* results in
218 debug messages for connection and for all messages sent to and received from
219 the server. A value of 2 for *level* results in these messages being
220 timestamped.
221
222 .. versionchanged:: 3.5 Added debuglevel 2.
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224
Georg Brandl18244152009-09-02 20:34:52 +0000225.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Georg Brandl18244152009-09-02 20:34:52 +0000227 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000228 concatenated to the command, separated by a space.
229
230 This returns a 2-tuple composed of a numeric response code and the actual
231 response line (multiline responses are joined into one long line.)
232
233 In normal operation it should not be necessary to call this method explicitly.
234 It is used to implement other methods and may be useful for testing private
235 extensions.
236
237 If the connection to the server is lost while waiting for the reply,
238 :exc:`SMTPServerDisconnected` will be raised.
239
240
R David Murray14ee3cf2013-04-13 14:40:33 -0400241.. method:: SMTP.connect(host='localhost', port=0)
242
243 Connect to a host on a given port. The defaults are to connect to the local
244 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
245 followed by a number, that suffix will be stripped off and the number
246 interpreted as the port number to use. This method is automatically invoked by
247 the constructor if a host is specified during instantiation. Returns a
248 2-tuple of the response code and message sent by the server in its
249 connection response.
250
Steve Dower44f91c32019-06-27 10:47:59 -0700251 .. audit-event:: smtplib.connect self,host,port smtplib.SMTP.connect
Steve Dower60419a72019-06-24 08:42:54 -0700252
R David Murray14ee3cf2013-04-13 14:40:33 -0400253
Georg Brandl18244152009-09-02 20:34:52 +0000254.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256 Identify yourself to the SMTP server using ``HELO``. The hostname argument
257 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000258 The message returned by the server is stored as the :attr:`helo_resp` attribute
259 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261 In normal operation it should not be necessary to call this method explicitly.
262 It will be implicitly called by the :meth:`sendmail` when necessary.
263
264
Georg Brandl18244152009-09-02 20:34:52 +0000265.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
268 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000269 response for ESMTP option and store them for use by :meth:`has_extn`.
270 Also sets several informational attributes: the message returned by
271 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000272 is set to true or false depending on whether the server supports ESMTP, and
273 :attr:`esmtp_features` will be a dictionary containing the names of the
R David Murray76e13c12014-07-03 14:47:46 -0400274 SMTP service extensions this server supports, and their parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
277 necessary to call this method explicitly. It will be implicitly called by
278 :meth:`sendmail` when necessary.
279
Christian Heimes679db4a2008-01-18 09:56:22 +0000280.. method:: SMTP.ehlo_or_helo_if_needed()
281
Ville Skyttäda120632018-08-13 06:39:19 +0300282 This method calls :meth:`ehlo` and/or :meth:`helo` if there has been no
Christian Heimes679db4a2008-01-18 09:56:22 +0000283 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
284 first.
285
Georg Brandl1f01deb2009-01-03 22:47:39 +0000286 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000287 The server didn't reply properly to the ``HELO`` greeting.
288
Georg Brandl116aa622007-08-15 14:28:22 +0000289.. method:: SMTP.has_extn(name)
290
291 Return :const:`True` if *name* is in the set of SMTP service extensions returned
292 by the server, :const:`False` otherwise. Case is ignored.
293
294
295.. method:: SMTP.verify(address)
296
297 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
298 tuple consisting of code 250 and a full :rfc:`822` address (including human
299 name) if the user address is valid. Otherwise returns an SMTP error code of 400
300 or greater and an error string.
301
302 .. note::
303
304 Many sites disable SMTP ``VRFY`` in order to foil spammers.
305
306
Barry Warsawc5ea7542015-07-09 10:39:55 -0400307.. method:: SMTP.login(user, password, *, initial_response_ok=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309 Log in on an SMTP server that requires authentication. The arguments are the
310 username and the password to authenticate with. If there has been no previous
311 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
312 first. This method will return normally if the authentication was successful, or
313 may raise the following exceptions:
314
315 :exc:`SMTPHeloError`
316 The server didn't reply properly to the ``HELO`` greeting.
317
318 :exc:`SMTPAuthenticationError`
319 The server didn't accept the username/password combination.
320
R David Murraycee7cf62015-05-16 13:58:14 -0400321 :exc:`SMTPNotSupportedError`
322 The ``AUTH`` command is not supported by the server.
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324 :exc:`SMTPException`
325 No suitable authentication method was found.
326
R David Murray76e13c12014-07-03 14:47:46 -0400327 Each of the authentication methods supported by :mod:`smtplib` are tried in
Barry Warsawc5ea7542015-07-09 10:39:55 -0400328 turn if they are advertised as supported by the server. See :meth:`auth`
329 for a list of supported authentication methods. *initial_response_ok* is
330 passed through to :meth:`auth`.
331
332 Optional keyword argument *initial_response_ok* specifies whether, for
333 authentication methods that support it, an "initial response" as specified
334 in :rfc:`4954` can be sent along with the ``AUTH`` command, rather than
335 requiring a challenge/response.
R David Murray76e13c12014-07-03 14:47:46 -0400336
R David Murraycee7cf62015-05-16 13:58:14 -0400337 .. versionchanged:: 3.5
Barry Warsawc5ea7542015-07-09 10:39:55 -0400338 :exc:`SMTPNotSupportedError` may be raised, and the
339 *initial_response_ok* parameter was added.
R David Murraycee7cf62015-05-16 13:58:14 -0400340
R David Murray76e13c12014-07-03 14:47:46 -0400341
Barry Warsawc5ea7542015-07-09 10:39:55 -0400342.. method:: SMTP.auth(mechanism, authobject, *, initial_response_ok=True)
R David Murray76e13c12014-07-03 14:47:46 -0400343
344 Issue an ``SMTP`` ``AUTH`` command for the specified authentication
345 *mechanism*, and handle the challenge response via *authobject*.
346
347 *mechanism* specifies which authentication mechanism is to
348 be used as argument to the ``AUTH`` command; the valid values are
349 those listed in the ``auth`` element of :attr:`esmtp_features`.
350
Barry Warsawc5ea7542015-07-09 10:39:55 -0400351 *authobject* must be a callable object taking an optional single argument:
R David Murray76e13c12014-07-03 14:47:46 -0400352
Barry Warsawc5ea7542015-07-09 10:39:55 -0400353 data = authobject(challenge=None)
R David Murray76e13c12014-07-03 14:47:46 -0400354
Barry Warsawc5ea7542015-07-09 10:39:55 -0400355 If optional keyword argument *initial_response_ok* is true,
356 ``authobject()`` will be called first with no argument. It can return the
Sebastian Rittau78deb7f2018-09-10 19:29:43 +0200357 :rfc:`4954` "initial response" ASCII ``str`` which will be encoded and sent with
Barry Warsawc5ea7542015-07-09 10:39:55 -0400358 the ``AUTH`` command as below. If the ``authobject()`` does not support an
359 initial response (e.g. because it requires a challenge), it should return
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300360 ``None`` when called with ``challenge=None``. If *initial_response_ok* is
361 false, then ``authobject()`` will not be called first with ``None``.
Barry Warsawc5ea7542015-07-09 10:39:55 -0400362
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300363 If the initial response check returns ``None``, or if *initial_response_ok* is
Barry Warsawc5ea7542015-07-09 10:39:55 -0400364 false, ``authobject()`` will be called to process the server's challenge
365 response; the *challenge* argument it is passed will be a ``bytes``. It
Sebastian Rittau78deb7f2018-09-10 19:29:43 +0200366 should return ASCII ``str`` *data* that will be base64 encoded and sent to the
Barry Warsawc5ea7542015-07-09 10:39:55 -0400367 server.
R David Murray76e13c12014-07-03 14:47:46 -0400368
369 The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``,
370 and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``,
371 ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively. They all require
372 that the ``user`` and ``password`` properties of the ``SMTP`` instance are
373 set to appropriate values.
374
375 User code does not normally need to call ``auth`` directly, but can instead
Barry Warsawc5ea7542015-07-09 10:39:55 -0400376 call the :meth:`login` method, which will try each of the above mechanisms
377 in turn, in the order listed. ``auth`` is exposed to facilitate the
378 implementation of authentication methods not (or not yet) supported
379 directly by :mod:`smtplib`.
R David Murray76e13c12014-07-03 14:47:46 -0400380
381 .. versionadded:: 3.5
382
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Antoine Pitroue0650202011-05-18 18:03:09 +0200384.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000385
386 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
387 commands that follow will be encrypted. You should then call :meth:`ehlo`
388 again.
389
Ville Skyttäda120632018-08-13 06:39:19 +0300390 If *keyfile* and *certfile* are provided, they are used to create an
391 :class:`ssl.SSLContext`.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Ville Skyttäda120632018-08-13 06:39:19 +0300393 Optional *context* parameter is an :class:`ssl.SSLContext` object; This is
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300394 an alternative to using a keyfile and a certfile and if specified both
395 *keyfile* and *certfile* should be ``None``.
Antoine Pitroue0650202011-05-18 18:03:09 +0200396
Christian Heimes679db4a2008-01-18 09:56:22 +0000397 If there has been no previous ``EHLO`` or ``HELO`` command this session,
398 this method tries ESMTP ``EHLO`` first.
399
Ville Skyttäda120632018-08-13 06:39:19 +0300400 .. deprecated:: 3.6
401
402 *keyfile* and *certfile* are deprecated in favor of *context*.
403 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
404 :func:`ssl.create_default_context` select the system's trusted CA
405 certificates for you.
406
Christian Heimes679db4a2008-01-18 09:56:22 +0000407 :exc:`SMTPHeloError`
408 The server didn't reply properly to the ``HELO`` greeting.
409
R David Murraycee7cf62015-05-16 13:58:14 -0400410 :exc:`SMTPNotSupportedError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000411 The server does not support the STARTTLS extension.
412
Christian Heimes679db4a2008-01-18 09:56:22 +0000413 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000414 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000415
Antoine Pitroue0650202011-05-18 18:03:09 +0200416 .. versionchanged:: 3.3
417 *context* was added.
418
Christian Heimesa5768f72013-12-02 20:44:17 +0100419 .. versionchanged:: 3.4
420 The method now supports hostname check with
421 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
422 :data:`~ssl.HAS_SNI`).
423
R David Murraycee7cf62015-05-16 13:58:14 -0400424 .. versionchanged:: 3.5
425 The error raised for lack of STARTTLS support is now the
426 :exc:`SMTPNotSupportedError` subclass instead of the base
427 :exc:`SMTPException`.
428
Georg Brandl116aa622007-08-15 14:28:22 +0000429
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200430.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
Georg Brandl116aa622007-08-15 14:28:22 +0000431
432 Send mail. The required arguments are an :rfc:`822` from-address string, a list
433 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
434 address), and a message string. The caller may pass a list of ESMTP options
435 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
436 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
437 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
438 options to different recipients you have to use the low-level methods such as
439 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
440
441 .. note::
442
443 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000444 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000445 message headers in any way.
446
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600447 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000448 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600449 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
450 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000451
Georg Brandl116aa622007-08-15 14:28:22 +0000452 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
453 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
454 each of the specified options will be passed to it (if the option is in the
455 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
456 and ESMTP options suppressed.
457
458 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000459 recipient. Otherwise it will raise an exception. That is, if this method does
460 not raise an exception, then someone should get your mail. If this method does
461 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000462 recipient that was refused. Each entry contains a tuple of the SMTP error code
463 and the accompanying error message sent by the server.
464
R David Murraycee7cf62015-05-16 13:58:14 -0400465 If ``SMTPUTF8`` is included in *mail_options*, and the server supports it,
Raymond Hettinger624e2222016-08-30 13:25:06 -0700466 *from_addr* and *to_addrs* may contain non-ASCII characters.
R David Murraycee7cf62015-05-16 13:58:14 -0400467
Georg Brandl116aa622007-08-15 14:28:22 +0000468 This method may raise the following exceptions:
469
470 :exc:`SMTPRecipientsRefused`
471 All recipients were refused. Nobody got the mail. The :attr:`recipients`
472 attribute of the exception object is a dictionary with information about the
473 refused recipients (like the one returned when at least one recipient was
474 accepted).
475
476 :exc:`SMTPHeloError`
477 The server didn't reply properly to the ``HELO`` greeting.
478
479 :exc:`SMTPSenderRefused`
480 The server didn't accept the *from_addr*.
481
482 :exc:`SMTPDataError`
483 The server replied with an unexpected error code (other than a refusal of a
484 recipient).
485
R David Murraycee7cf62015-05-16 13:58:14 -0400486 :exc:`SMTPNotSupportedError`
487 ``SMTPUTF8`` was given in the *mail_options* but is not supported by the
488 server.
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490 Unless otherwise noted, the connection will be open even after an exception is
491 raised.
492
Georg Brandl61063cc2012-06-24 22:48:30 +0200493 .. versionchanged:: 3.2
494 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000495
R David Murraycee7cf62015-05-16 13:58:14 -0400496 .. versionchanged:: 3.5
497 ``SMTPUTF8`` support added, and :exc:`SMTPNotSupportedError` may be
498 raised if ``SMTPUTF8`` is specified but the server does not support it.
499
R. David Murray7dff9e02010-11-08 17:15:13 +0000500
R David Murrayac4e5ab2011-07-02 21:03:19 -0400501.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200502 mail_options=(), rcpt_options=())
R. David Murray7dff9e02010-11-08 17:15:13 +0000503
504 This is a convenience method for calling :meth:`sendmail` with the message
505 represented by an :class:`email.message.Message` object. The arguments have
506 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
507 object.
508
R David Murrayac4e5ab2011-07-02 21:03:19 -0400509 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
510 those arguments with addresses extracted from the headers of *msg* as
R David Murray83084442015-05-17 19:27:22 -0400511 specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender`
R David Murrayac4e5ab2011-07-02 21:03:19 -0400512 field if it is present, and otherwise to the :mailheader:`From` field.
Raymond Hettinger624e2222016-08-30 13:25:06 -0700513 *to_addrs* combines the values (if any) of the :mailheader:`To`,
R David Murrayac4e5ab2011-07-02 21:03:19 -0400514 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
515 set of :mailheader:`Resent-*` headers appear in the message, the regular
516 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
517 If the message contains more than one set of :mailheader:`Resent-*` headers,
518 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
519 the most recent set of :mailheader:`Resent-` headers.
520
521 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000522 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400523 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
524 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
525 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
R David Murray83084442015-05-17 19:27:22 -0400526 in *msg*. If any of the addresses in *from_addr* and *to_addrs* contain
527 non-ASCII characters and the server does not advertise ``SMTPUTF8`` support,
528 an :exc:`SMTPNotSupported` error is raised. Otherwise the ``Message`` is
529 serialized with a clone of its :mod:`~email.policy` with the
530 :attr:`~email.policy.EmailPolicy.utf8` attribute set to ``True``, and
531 ``SMTPUTF8`` and ``BODY=8BITMIME`` are added to *mail_options*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000532
533 .. versionadded:: 3.2
534
R David Murray83084442015-05-17 19:27:22 -0400535 .. versionadded:: 3.5
536 Support for internationalized addresses (``SMTPUTF8``).
537
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539.. method:: SMTP.quit()
540
Christian Heimesba4af492008-03-28 00:55:15 +0000541 Terminate the SMTP session and close the connection. Return the result of
542 the SMTP ``QUIT`` command.
543
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
546``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
547Normally these do not need to be called directly, so they are not documented
548here. For details, consult the module code.
549
550
551.. _smtp-example:
552
553SMTP Example
554------------
555
556This example prompts the user for addresses needed in the message envelope ('To'
557and 'From' addresses), and the message to be delivered. Note that the headers
558to be included with the message must be included in the message as entered; this
559example doesn't do any processing of the :rfc:`822` headers. In particular, the
560'To' and 'From' addresses must be included in the message headers explicitly. ::
561
562 import smtplib
563
Georg Brandl116aa622007-08-15 14:28:22 +0000564 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000565 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567 fromaddr = prompt("From: ")
568 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000569 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000570
571 # Add the From: and To: headers at the start!
572 msg = ("From: %s\r\nTo: %s\r\n\r\n"
573 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000574 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000575 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000576 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000577 except EOFError:
578 break
579 if not line:
580 break
581 msg = msg + line
582
Georg Brandl6911e3c2007-09-04 07:15:32 +0000583 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585 server = smtplib.SMTP('localhost')
586 server.set_debuglevel(1)
587 server.sendmail(fromaddr, toaddrs, msg)
588 server.quit()
589
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000590.. note::
591
592 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000593 construct an email message, which you can then send
594 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.