blob: 8771f10938044dfc4466014dc8541cd439ac8764 [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 Dower60419a72019-06-24 08:42:54 -070058 All commands will raise an :ref:`auditing event <auditing>`
59 ``smtplib.SMTP.send`` with arguments ``self`` and ``data``,
60 where ``data`` is the bytes about to be sent to the remote host.
61
Antoine Pitrou45456a02011-04-26 18:53:42 +020062 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040063 Support for the :keyword:`with` statement was added.
64
Senthil Kumaranb351a482011-07-31 09:14:17 +080065 .. versionchanged:: 3.3
66 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000067
R David Murraycee7cf62015-05-16 13:58:14 -040068 .. versionadded:: 3.5
69 The SMTPUTF8 extension (:rfc:`6531`) is now supported.
70
71
R David Murray36beb662013-06-23 15:47:50 -040072.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \
73 certfile=None [, timeout], context=None, \
74 source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000075
Martin Panter7462b6492015-11-02 03:37:02 +000076 An :class:`SMTP_SSL` instance behaves exactly the same as instances of
Georg Brandl116aa622007-08-15 14:28:22 +000077 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000078 required from the beginning of the connection and using :meth:`starttls` is
79 not appropriate. If *host* is not specified, the local host is used. If
R David Murray36beb662013-06-23 15:47:50 -040080 *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010081 arguments *local_hostname*, *timeout* and *source_address* have the same
82 meaning as they do in the :class:`SMTP` class. *context*, also optional,
Martin Panterc04fb562016-02-10 05:44:01 +000083 can contain a :class:`~ssl.SSLContext` and allows configuring various
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010084 aspects of the secure connection. Please read :ref:`ssl-security` for
85 best practices.
86
87 *keyfile* and *certfile* are a legacy alternative to *context*, and can
88 point to a PEM formatted private key and certificate chain file for the
89 SSL connection.
Georg Brandl116aa622007-08-15 14:28:22 +000090
Antoine Pitroue0650202011-05-18 18:03:09 +020091 .. versionchanged:: 3.3
92 *context* was added.
93
Senthil Kumaranb351a482011-07-31 09:14:17 +080094 .. versionchanged:: 3.3
95 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000096
Christian Heimesa5768f72013-12-02 20:44:17 +010097 .. versionchanged:: 3.4
98 The class now supports hostname check with
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010099 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
100 :data:`ssl.HAS_SNI`).
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800101
Christian Heimesd0486372016-09-10 23:23:33 +0200102 .. deprecated:: 3.6
103
104 *keyfile* and *certfile* are deprecated in favor of *context*.
105 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
106 :func:`ssl.create_default_context` select the system's trusted CA
107 certificates for you.
108
109
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800110.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800113 standard SMTP client. It's common to use Unix sockets for LMTP, so our
114 :meth:`connect` method must support that as well as a regular host:port
Senthil Kumaranb351a482011-07-31 09:14:17 +0800115 server. The optional arguments local_hostname and source_address have the
R David Murray021362d2013-06-23 16:05:44 -0400116 same meaning as they do in the :class:`SMTP` class. To specify a Unix
117 socket, you must use an absolute path for *host*, starting with a '/'.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
R David Murray021362d2013-06-23 16:05:44 -0400119 Authentication is supported, using the regular SMTP mechanism. When using a
120 Unix socket, LMTP generally don't support or require any authentication, but
121 your mileage might vary.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124A nice selection of exceptions is defined as well:
125
126
127.. exception:: SMTPException
128
R David Murray8a345962013-04-14 06:46:35 -0400129 Subclass of :exc:`OSError` that is the base exception class for all
Ned Deily7cf5e612013-08-13 01:15:14 -0700130 the other exceptions provided by this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Larry Hastings3732ed22014-03-15 21:13:56 -0700132 .. versionchanged:: 3.4
133 SMTPException became subclass of :exc:`OSError`
134
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136.. exception:: SMTPServerDisconnected
137
138 This exception is raised when the server unexpectedly disconnects, or when an
139 attempt is made to use the :class:`SMTP` instance before connecting it to a
140 server.
141
142
143.. exception:: SMTPResponseException
144
145 Base class for all exceptions that include an SMTP error code. These exceptions
146 are generated in some instances when the SMTP server returns an error code. The
147 error code is stored in the :attr:`smtp_code` attribute of the error, and the
148 :attr:`smtp_error` attribute is set to the error message.
149
150
151.. exception:: SMTPSenderRefused
152
153 Sender address refused. In addition to the attributes set by on all
154 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
155 the SMTP server refused.
156
157
158.. exception:: SMTPRecipientsRefused
159
160 All recipient addresses refused. The errors for each recipient are accessible
161 through the attribute :attr:`recipients`, which is a dictionary of exactly the
162 same sort as :meth:`SMTP.sendmail` returns.
163
164
165.. exception:: SMTPDataError
166
167 The SMTP server refused to accept the message data.
168
169
170.. exception:: SMTPConnectError
171
172 Error occurred during establishment of a connection with the server.
173
174
175.. exception:: SMTPHeloError
176
177 The server refused our ``HELO`` message.
178
179
R David Murraycee7cf62015-05-16 13:58:14 -0400180.. exception:: SMTPNotSupportedError
181
182 The command or option attempted is not supported by the server.
183
184 .. versionadded:: 3.5
185
186
Georg Brandl116aa622007-08-15 14:28:22 +0000187.. exception:: SMTPAuthenticationError
188
189 SMTP authentication went wrong. Most probably the server didn't accept the
190 username/password combination provided.
191
192
193.. seealso::
194
195 :rfc:`821` - Simple Mail Transfer Protocol
196 Protocol definition for SMTP. This document covers the model, operating
197 procedure, and protocol details for SMTP.
198
199 :rfc:`1869` - SMTP Service Extensions
200 Definition of the ESMTP extensions for SMTP. This describes a framework for
201 extending SMTP with new commands, supporting dynamic discovery of the commands
202 provided by the server, and defines a few additional commands.
203
204
205.. _smtp-objects:
206
207SMTP Objects
208------------
209
210An :class:`SMTP` instance has the following methods:
211
212
213.. method:: SMTP.set_debuglevel(level)
214
R David Murray2e6ad422015-04-16 17:24:52 -0400215 Set the debug output level. A value of 1 or ``True`` for *level* results in
216 debug messages for connection and for all messages sent to and received from
217 the server. A value of 2 for *level* results in these messages being
218 timestamped.
219
220 .. versionchanged:: 3.5 Added debuglevel 2.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222
Georg Brandl18244152009-09-02 20:34:52 +0000223.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Georg Brandl18244152009-09-02 20:34:52 +0000225 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000226 concatenated to the command, separated by a space.
227
228 This returns a 2-tuple composed of a numeric response code and the actual
229 response line (multiline responses are joined into one long line.)
230
231 In normal operation it should not be necessary to call this method explicitly.
232 It is used to implement other methods and may be useful for testing private
233 extensions.
234
235 If the connection to the server is lost while waiting for the reply,
236 :exc:`SMTPServerDisconnected` will be raised.
237
238
R David Murray14ee3cf2013-04-13 14:40:33 -0400239.. method:: SMTP.connect(host='localhost', port=0)
240
241 Connect to a host on a given port. The defaults are to connect to the local
242 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
243 followed by a number, that suffix will be stripped off and the number
244 interpreted as the port number to use. This method is automatically invoked by
245 the constructor if a host is specified during instantiation. Returns a
246 2-tuple of the response code and message sent by the server in its
247 connection response.
248
Steve Dower60419a72019-06-24 08:42:54 -0700249 .. audit-event:: smtplib.SMTP.connect "self host port"
250
R David Murray14ee3cf2013-04-13 14:40:33 -0400251
Georg Brandl18244152009-09-02 20:34:52 +0000252.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254 Identify yourself to the SMTP server using ``HELO``. The hostname argument
255 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000256 The message returned by the server is stored as the :attr:`helo_resp` attribute
257 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259 In normal operation it should not be necessary to call this method explicitly.
260 It will be implicitly called by the :meth:`sendmail` when necessary.
261
262
Georg Brandl18244152009-09-02 20:34:52 +0000263.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
266 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000267 response for ESMTP option and store them for use by :meth:`has_extn`.
268 Also sets several informational attributes: the message returned by
269 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000270 is set to true or false depending on whether the server supports ESMTP, and
271 :attr:`esmtp_features` will be a dictionary containing the names of the
R David Murray76e13c12014-07-03 14:47:46 -0400272 SMTP service extensions this server supports, and their parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
275 necessary to call this method explicitly. It will be implicitly called by
276 :meth:`sendmail` when necessary.
277
Christian Heimes679db4a2008-01-18 09:56:22 +0000278.. method:: SMTP.ehlo_or_helo_if_needed()
279
Ville Skyttäda120632018-08-13 06:39:19 +0300280 This method calls :meth:`ehlo` and/or :meth:`helo` if there has been no
Christian Heimes679db4a2008-01-18 09:56:22 +0000281 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
282 first.
283
Georg Brandl1f01deb2009-01-03 22:47:39 +0000284 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000285 The server didn't reply properly to the ``HELO`` greeting.
286
Georg Brandl116aa622007-08-15 14:28:22 +0000287.. method:: SMTP.has_extn(name)
288
289 Return :const:`True` if *name* is in the set of SMTP service extensions returned
290 by the server, :const:`False` otherwise. Case is ignored.
291
292
293.. method:: SMTP.verify(address)
294
295 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
296 tuple consisting of code 250 and a full :rfc:`822` address (including human
297 name) if the user address is valid. Otherwise returns an SMTP error code of 400
298 or greater and an error string.
299
300 .. note::
301
302 Many sites disable SMTP ``VRFY`` in order to foil spammers.
303
304
Barry Warsawc5ea7542015-07-09 10:39:55 -0400305.. method:: SMTP.login(user, password, *, initial_response_ok=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307 Log in on an SMTP server that requires authentication. The arguments are the
308 username and the password to authenticate with. If there has been no previous
309 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
310 first. This method will return normally if the authentication was successful, or
311 may raise the following exceptions:
312
313 :exc:`SMTPHeloError`
314 The server didn't reply properly to the ``HELO`` greeting.
315
316 :exc:`SMTPAuthenticationError`
317 The server didn't accept the username/password combination.
318
R David Murraycee7cf62015-05-16 13:58:14 -0400319 :exc:`SMTPNotSupportedError`
320 The ``AUTH`` command is not supported by the server.
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322 :exc:`SMTPException`
323 No suitable authentication method was found.
324
R David Murray76e13c12014-07-03 14:47:46 -0400325 Each of the authentication methods supported by :mod:`smtplib` are tried in
Barry Warsawc5ea7542015-07-09 10:39:55 -0400326 turn if they are advertised as supported by the server. See :meth:`auth`
327 for a list of supported authentication methods. *initial_response_ok* is
328 passed through to :meth:`auth`.
329
330 Optional keyword argument *initial_response_ok* specifies whether, for
331 authentication methods that support it, an "initial response" as specified
332 in :rfc:`4954` can be sent along with the ``AUTH`` command, rather than
333 requiring a challenge/response.
R David Murray76e13c12014-07-03 14:47:46 -0400334
R David Murraycee7cf62015-05-16 13:58:14 -0400335 .. versionchanged:: 3.5
Barry Warsawc5ea7542015-07-09 10:39:55 -0400336 :exc:`SMTPNotSupportedError` may be raised, and the
337 *initial_response_ok* parameter was added.
R David Murraycee7cf62015-05-16 13:58:14 -0400338
R David Murray76e13c12014-07-03 14:47:46 -0400339
Barry Warsawc5ea7542015-07-09 10:39:55 -0400340.. method:: SMTP.auth(mechanism, authobject, *, initial_response_ok=True)
R David Murray76e13c12014-07-03 14:47:46 -0400341
342 Issue an ``SMTP`` ``AUTH`` command for the specified authentication
343 *mechanism*, and handle the challenge response via *authobject*.
344
345 *mechanism* specifies which authentication mechanism is to
346 be used as argument to the ``AUTH`` command; the valid values are
347 those listed in the ``auth`` element of :attr:`esmtp_features`.
348
Barry Warsawc5ea7542015-07-09 10:39:55 -0400349 *authobject* must be a callable object taking an optional single argument:
R David Murray76e13c12014-07-03 14:47:46 -0400350
Barry Warsawc5ea7542015-07-09 10:39:55 -0400351 data = authobject(challenge=None)
R David Murray76e13c12014-07-03 14:47:46 -0400352
Barry Warsawc5ea7542015-07-09 10:39:55 -0400353 If optional keyword argument *initial_response_ok* is true,
354 ``authobject()`` will be called first with no argument. It can return the
Sebastian Rittau78deb7f2018-09-10 19:29:43 +0200355 :rfc:`4954` "initial response" ASCII ``str`` which will be encoded and sent with
Barry Warsawc5ea7542015-07-09 10:39:55 -0400356 the ``AUTH`` command as below. If the ``authobject()`` does not support an
357 initial response (e.g. because it requires a challenge), it should return
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300358 ``None`` when called with ``challenge=None``. If *initial_response_ok* is
359 false, then ``authobject()`` will not be called first with ``None``.
Barry Warsawc5ea7542015-07-09 10:39:55 -0400360
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300361 If the initial response check returns ``None``, or if *initial_response_ok* is
Barry Warsawc5ea7542015-07-09 10:39:55 -0400362 false, ``authobject()`` will be called to process the server's challenge
363 response; the *challenge* argument it is passed will be a ``bytes``. It
Sebastian Rittau78deb7f2018-09-10 19:29:43 +0200364 should return ASCII ``str`` *data* that will be base64 encoded and sent to the
Barry Warsawc5ea7542015-07-09 10:39:55 -0400365 server.
R David Murray76e13c12014-07-03 14:47:46 -0400366
367 The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``,
368 and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``,
369 ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively. They all require
370 that the ``user`` and ``password`` properties of the ``SMTP`` instance are
371 set to appropriate values.
372
373 User code does not normally need to call ``auth`` directly, but can instead
Barry Warsawc5ea7542015-07-09 10:39:55 -0400374 call the :meth:`login` method, which will try each of the above mechanisms
375 in turn, in the order listed. ``auth`` is exposed to facilitate the
376 implementation of authentication methods not (or not yet) supported
377 directly by :mod:`smtplib`.
R David Murray76e13c12014-07-03 14:47:46 -0400378
379 .. versionadded:: 3.5
380
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Antoine Pitroue0650202011-05-18 18:03:09 +0200382.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
385 commands that follow will be encrypted. You should then call :meth:`ehlo`
386 again.
387
Ville Skyttäda120632018-08-13 06:39:19 +0300388 If *keyfile* and *certfile* are provided, they are used to create an
389 :class:`ssl.SSLContext`.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Ville Skyttäda120632018-08-13 06:39:19 +0300391 Optional *context* parameter is an :class:`ssl.SSLContext` object; This is
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300392 an alternative to using a keyfile and a certfile and if specified both
393 *keyfile* and *certfile* should be ``None``.
Antoine Pitroue0650202011-05-18 18:03:09 +0200394
Christian Heimes679db4a2008-01-18 09:56:22 +0000395 If there has been no previous ``EHLO`` or ``HELO`` command this session,
396 this method tries ESMTP ``EHLO`` first.
397
Ville Skyttäda120632018-08-13 06:39:19 +0300398 .. deprecated:: 3.6
399
400 *keyfile* and *certfile* are deprecated in favor of *context*.
401 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
402 :func:`ssl.create_default_context` select the system's trusted CA
403 certificates for you.
404
Christian Heimes679db4a2008-01-18 09:56:22 +0000405 :exc:`SMTPHeloError`
406 The server didn't reply properly to the ``HELO`` greeting.
407
R David Murraycee7cf62015-05-16 13:58:14 -0400408 :exc:`SMTPNotSupportedError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000409 The server does not support the STARTTLS extension.
410
Christian Heimes679db4a2008-01-18 09:56:22 +0000411 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000412 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000413
Antoine Pitroue0650202011-05-18 18:03:09 +0200414 .. versionchanged:: 3.3
415 *context* was added.
416
Christian Heimesa5768f72013-12-02 20:44:17 +0100417 .. versionchanged:: 3.4
418 The method now supports hostname check with
419 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
420 :data:`~ssl.HAS_SNI`).
421
R David Murraycee7cf62015-05-16 13:58:14 -0400422 .. versionchanged:: 3.5
423 The error raised for lack of STARTTLS support is now the
424 :exc:`SMTPNotSupportedError` subclass instead of the base
425 :exc:`SMTPException`.
426
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200428.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430 Send mail. The required arguments are an :rfc:`822` from-address string, a list
431 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
432 address), and a message string. The caller may pass a list of ESMTP options
433 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
434 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
435 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
436 options to different recipients you have to use the low-level methods such as
437 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
438
439 .. note::
440
441 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000442 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000443 message headers in any way.
444
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600445 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000446 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600447 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
448 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000449
Georg Brandl116aa622007-08-15 14:28:22 +0000450 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
451 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
452 each of the specified options will be passed to it (if the option is in the
453 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
454 and ESMTP options suppressed.
455
456 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000457 recipient. Otherwise it will raise an exception. That is, if this method does
458 not raise an exception, then someone should get your mail. If this method does
459 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000460 recipient that was refused. Each entry contains a tuple of the SMTP error code
461 and the accompanying error message sent by the server.
462
R David Murraycee7cf62015-05-16 13:58:14 -0400463 If ``SMTPUTF8`` is included in *mail_options*, and the server supports it,
Raymond Hettinger624e2222016-08-30 13:25:06 -0700464 *from_addr* and *to_addrs* may contain non-ASCII characters.
R David Murraycee7cf62015-05-16 13:58:14 -0400465
Georg Brandl116aa622007-08-15 14:28:22 +0000466 This method may raise the following exceptions:
467
468 :exc:`SMTPRecipientsRefused`
469 All recipients were refused. Nobody got the mail. The :attr:`recipients`
470 attribute of the exception object is a dictionary with information about the
471 refused recipients (like the one returned when at least one recipient was
472 accepted).
473
474 :exc:`SMTPHeloError`
475 The server didn't reply properly to the ``HELO`` greeting.
476
477 :exc:`SMTPSenderRefused`
478 The server didn't accept the *from_addr*.
479
480 :exc:`SMTPDataError`
481 The server replied with an unexpected error code (other than a refusal of a
482 recipient).
483
R David Murraycee7cf62015-05-16 13:58:14 -0400484 :exc:`SMTPNotSupportedError`
485 ``SMTPUTF8`` was given in the *mail_options* but is not supported by the
486 server.
487
Georg Brandl116aa622007-08-15 14:28:22 +0000488 Unless otherwise noted, the connection will be open even after an exception is
489 raised.
490
Georg Brandl61063cc2012-06-24 22:48:30 +0200491 .. versionchanged:: 3.2
492 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000493
R David Murraycee7cf62015-05-16 13:58:14 -0400494 .. versionchanged:: 3.5
495 ``SMTPUTF8`` support added, and :exc:`SMTPNotSupportedError` may be
496 raised if ``SMTPUTF8`` is specified but the server does not support it.
497
R. David Murray7dff9e02010-11-08 17:15:13 +0000498
R David Murrayac4e5ab2011-07-02 21:03:19 -0400499.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200500 mail_options=(), rcpt_options=())
R. David Murray7dff9e02010-11-08 17:15:13 +0000501
502 This is a convenience method for calling :meth:`sendmail` with the message
503 represented by an :class:`email.message.Message` object. The arguments have
504 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
505 object.
506
R David Murrayac4e5ab2011-07-02 21:03:19 -0400507 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
508 those arguments with addresses extracted from the headers of *msg* as
R David Murray83084442015-05-17 19:27:22 -0400509 specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender`
R David Murrayac4e5ab2011-07-02 21:03:19 -0400510 field if it is present, and otherwise to the :mailheader:`From` field.
Raymond Hettinger624e2222016-08-30 13:25:06 -0700511 *to_addrs* combines the values (if any) of the :mailheader:`To`,
R David Murrayac4e5ab2011-07-02 21:03:19 -0400512 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
513 set of :mailheader:`Resent-*` headers appear in the message, the regular
514 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
515 If the message contains more than one set of :mailheader:`Resent-*` headers,
516 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
517 the most recent set of :mailheader:`Resent-` headers.
518
519 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000520 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400521 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
522 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
523 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
R David Murray83084442015-05-17 19:27:22 -0400524 in *msg*. If any of the addresses in *from_addr* and *to_addrs* contain
525 non-ASCII characters and the server does not advertise ``SMTPUTF8`` support,
526 an :exc:`SMTPNotSupported` error is raised. Otherwise the ``Message`` is
527 serialized with a clone of its :mod:`~email.policy` with the
528 :attr:`~email.policy.EmailPolicy.utf8` attribute set to ``True``, and
529 ``SMTPUTF8`` and ``BODY=8BITMIME`` are added to *mail_options*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000530
531 .. versionadded:: 3.2
532
R David Murray83084442015-05-17 19:27:22 -0400533 .. versionadded:: 3.5
534 Support for internationalized addresses (``SMTPUTF8``).
535
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537.. method:: SMTP.quit()
538
Christian Heimesba4af492008-03-28 00:55:15 +0000539 Terminate the SMTP session and close the connection. Return the result of
540 the SMTP ``QUIT`` command.
541
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
544``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
545Normally these do not need to be called directly, so they are not documented
546here. For details, consult the module code.
547
548
549.. _smtp-example:
550
551SMTP Example
552------------
553
554This example prompts the user for addresses needed in the message envelope ('To'
555and 'From' addresses), and the message to be delivered. Note that the headers
556to be included with the message must be included in the message as entered; this
557example doesn't do any processing of the :rfc:`822` headers. In particular, the
558'To' and 'From' addresses must be included in the message headers explicitly. ::
559
560 import smtplib
561
Georg Brandl116aa622007-08-15 14:28:22 +0000562 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000563 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000564
565 fromaddr = prompt("From: ")
566 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000567 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569 # Add the From: and To: headers at the start!
570 msg = ("From: %s\r\nTo: %s\r\n\r\n"
571 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000572 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000573 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000574 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000575 except EOFError:
576 break
577 if not line:
578 break
579 msg = msg + line
580
Georg Brandl6911e3c2007-09-04 07:15:32 +0000581 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583 server = smtplib.SMTP('localhost')
584 server.set_debuglevel(1)
585 server.sendmail(fromaddr, toaddrs, msg)
586 server.quit()
587
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000588.. note::
589
590 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000591 construct an email message, which you can then send
592 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.