1:mod:`smtplib` --- SMTP protocol client
2=======================================
3
4.. module:: smtplib
5   :synopsis: SMTP protocol client (requires sockets).
6
7.. sectionauthor:: Eric S. Raymond <[email protected]>
8
9**Source code:** :source:`Lib/smtplib.py`
10
11.. index::
12   pair: SMTP; protocol
13   single: Simple Mail Transfer Protocol
14
15--------------
16
17The :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.. include:: ../includes/wasm-notavail.rst
23
24.. class:: SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None)
25
26   An :class:`SMTP` instance encapsulates an SMTP connection.  It has methods
27   that support a full repertoire of SMTP and ESMTP operations. If the optional
28   *host* and *port* parameters are given, the SMTP :meth:`connect` method is
29   called with those parameters during initialization.  If specified,
30   *local_hostname* is used as the FQDN of the local host in the HELO/EHLO
31   command.  Otherwise, the local hostname is found using
32   :func:`socket.getfqdn`.  If the :meth:`connect` call returns anything other
33   than a success code, an :exc:`SMTPConnectError` is raised. The optional
34   *timeout* parameter specifies a timeout in seconds for blocking operations
35   like the connection attempt (if not specified, the global default timeout
36   setting will be used).  If the timeout expires, :exc:`TimeoutError` is
37   raised.  The optional *source_address* parameter allows binding
38   to some specific source address in a machine with multiple network
39   interfaces, and/or to some specific source TCP port. It takes a 2-tuple
40   ``(host, port)``, for the socket to bind to as its source address before
41   connecting. If omitted (or if *host* or *port* are ``''`` and/or ``0``
42   respectively) the OS default behavior will be used.
43
44   For normal use, you should only require the initialization/connect,
45   :meth:`sendmail`, and :meth:`SMTP.quit` methods.
46   An example is included below.
47
48   The :class:`SMTP` class supports the :keyword:`with` statement.  When used
49   like this, the SMTP ``QUIT`` command is issued automatically when the
50   :keyword:`!with` statement exits.  E.g.::
51
52    >>> from smtplib import SMTP
53    >>> with SMTP("domain.org") as smtp:
54    ...     smtp.noop()
55    ...
56    (250, b'Ok')
57    >>>
58
59   .. audit-event:: smtplib.send self,data smtplib.SMTP
60
61      All commands will raise an :ref:`auditing event <auditing>`
62      ``smtplib.SMTP.send`` with arguments ``self`` and ``data``,
63      where ``data`` is the bytes about to be sent to the remote host.
64
65   .. versionchanged:: 3.3
66      Support for the :keyword:`with` statement was added.
67
68   .. versionchanged:: 3.3
69      source_address argument was added.
70
71   .. versionadded:: 3.5
72      The SMTPUTF8 extension (:rfc:`6531`) is now supported.
73
74   .. versionchanged:: 3.9
75      If the *timeout* parameter is set to be zero, it will raise a
76      :class:`ValueError` to prevent the creation of a non-blocking socket
77
78.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \
79                    certfile=None [, timeout], context=None, \
80                    source_address=None)
81
82   An :class:`SMTP_SSL` instance behaves exactly the same as instances of
83   :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
84   required from the beginning of the connection and using :meth:`starttls` is
85   not appropriate. If *host* is not specified, the local host is used. If
86   *port* is zero, the standard SMTP-over-SSL port (465) is used.  The optional
87   arguments *local_hostname*, *timeout* and *source_address* have the same
88   meaning as they do in the :class:`SMTP` class.  *context*, also optional,
89   can contain a :class:`~ssl.SSLContext` and allows configuring various
90   aspects of the secure connection.  Please read :ref:`ssl-security` for
91   best practices.
92
93   *keyfile* and *certfile* are a legacy alternative to *context*, and can
94   point to a PEM formatted private key and certificate chain file for the
95   SSL connection.
96
97   .. versionchanged:: 3.3
98      *context* was added.
99
100   .. versionchanged:: 3.3
101      source_address argument was added.
102
103   .. versionchanged:: 3.4
104      The class now supports hostname check with
105      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
106      :data:`ssl.HAS_SNI`).
107
108   .. deprecated:: 3.6
109
110       *keyfile* and *certfile* are deprecated in favor of *context*.
111       Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
112       :func:`ssl.create_default_context` select the system's trusted CA
113       certificates for you.
114
115   .. versionchanged:: 3.9
116      If the *timeout* parameter is set to be zero, it will raise a
117      :class:`ValueError` to prevent the creation of a non-blocking socket
118
119.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, \
120                source_address=None[, timeout])
121
122   The LMTP protocol, which is very similar to ESMTP, is heavily based on the
123   standard SMTP client. It's common to use Unix sockets for LMTP, so our
124   :meth:`connect` method must support that as well as a regular host:port
125   server. The optional arguments local_hostname and source_address have the
126   same meaning as they do in the :class:`SMTP` class. To specify a Unix
127   socket, you must use an absolute path for *host*, starting with a '/'.
128
129   Authentication is supported, using the regular SMTP mechanism. When using a
130   Unix socket, LMTP generally don't support or require any authentication, but
131   your mileage might vary.
132
133   .. versionchanged:: 3.9
134      The optional *timeout* parameter was added.
135
136
137A nice selection of exceptions is defined as well:
138
139
140.. exception:: SMTPException
141
142   Subclass of :exc:`OSError` that is the base exception class for all
143   the other exceptions provided by this module.
144
145   .. versionchanged:: 3.4
146      SMTPException became subclass of :exc:`OSError`
147
148
149.. exception:: SMTPServerDisconnected
150
151   This exception is raised when the server unexpectedly disconnects, or when an
152   attempt is made to use the :class:`SMTP` instance before connecting it to a
153   server.
154
155
156.. exception:: SMTPResponseException
157
158   Base class for all exceptions that include an SMTP error code. These exceptions
159   are generated in some instances when the SMTP server returns an error code.  The
160   error code is stored in the :attr:`smtp_code` attribute of the error, and the
161   :attr:`smtp_error` attribute is set to the error message.
162
163
164.. exception:: SMTPSenderRefused
165
166   Sender address refused.  In addition to the attributes set by on all
167   :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
168   the SMTP server refused.
169
170
171.. exception:: SMTPRecipientsRefused
172
173   All recipient addresses refused.  The errors for each recipient are accessible
174   through the attribute :attr:`recipients`, which is a dictionary of exactly the
175   same sort as :meth:`SMTP.sendmail` returns.
176
177
178.. exception:: SMTPDataError
179
180   The SMTP server refused to accept the message data.
181
182
183.. exception:: SMTPConnectError
184
185   Error occurred during establishment of a connection  with the server.
186
187
188.. exception:: SMTPHeloError
189
190   The server refused our ``HELO`` message.
191
192
193.. exception:: SMTPNotSupportedError
194
195    The command or option attempted is not supported by the server.
196
197    .. versionadded:: 3.5
198
199
200.. exception:: SMTPAuthenticationError
201
202   SMTP authentication went wrong.  Most probably the server didn't accept the
203   username/password combination provided.
204
205
206.. seealso::
207
208   :rfc:`821` - Simple Mail Transfer Protocol
209      Protocol definition for SMTP.  This document covers the model, operating
210      procedure, and protocol details for SMTP.
211
212   :rfc:`1869` - SMTP Service Extensions
213      Definition of the ESMTP extensions for SMTP.  This describes a framework for
214      extending SMTP with new commands, supporting dynamic discovery of the commands
215      provided by the server, and defines a few additional commands.
216
217
218.. _smtp-objects:
219
220SMTP Objects
221------------
222
223An :class:`SMTP` instance has the following methods:
224
225
226.. method:: SMTP.set_debuglevel(level)
227
228   Set the debug output level.  A value of 1 or ``True`` for *level* results in
229   debug messages for connection and for all messages sent to and received from
230   the server.  A value of 2 for *level* results in these messages being
231   timestamped.
232
233   .. versionchanged:: 3.5 Added debuglevel 2.
234
235
236.. method:: SMTP.docmd(cmd, args='')
237
238   Send a command *cmd* to the server.  The optional argument *args* is simply
239   concatenated to the command, separated by a space.
240
241   This returns a 2-tuple composed of a numeric response code and the actual
242   response line (multiline responses are joined into one long line.)
243
244   In normal operation it should not be necessary to call this method explicitly.
245   It is used to implement other methods and may be useful for testing private
246   extensions.
247
248   If the connection to the server is lost while waiting for the reply,
249   :exc:`SMTPServerDisconnected` will be raised.
250
251
252.. method:: SMTP.connect(host='localhost', port=0)
253
254   Connect to a host on a given port.  The defaults are to connect to the local
255   host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
256   followed by a number, that suffix will be stripped off and the number
257   interpreted as the port number to use. This method is automatically invoked by
258   the constructor if a host is specified during instantiation.  Returns a
259   2-tuple of the response code and message sent by the server in its
260   connection response.
261
262   .. audit-event:: smtplib.connect self,host,port smtplib.SMTP.connect
263
264
265.. method:: SMTP.helo(name='')
266
267   Identify yourself to the SMTP server using ``HELO``.  The hostname argument
268   defaults to the fully qualified domain name of the local host.
269   The message returned by the server is stored as the :attr:`helo_resp` attribute
270   of the object.
271
272   In normal operation it should not be necessary to call this method explicitly.
273   It will be implicitly called by the :meth:`sendmail` when necessary.
274
275
276.. method:: SMTP.ehlo(name='')
277
278   Identify yourself to an ESMTP server using ``EHLO``.  The hostname argument
279   defaults to the fully qualified domain name of the local host.  Examine the
280   response for ESMTP option and store them for use by :meth:`has_extn`.
281   Also sets several informational attributes: the message returned by
282   the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
283   is set to ``True`` or ``False`` depending on whether the server supports
284   ESMTP, and :attr:`esmtp_features` will be a dictionary containing the names
285   of the SMTP service extensions this server supports, and their parameters
286   (if any).
287
288   Unless you wish to use :meth:`has_extn` before sending mail, it should not be
289   necessary to call this method explicitly.  It will be implicitly called by
290   :meth:`sendmail` when necessary.
291
292.. method:: SMTP.ehlo_or_helo_if_needed()
293
294   This method calls :meth:`ehlo` and/or :meth:`helo` if there has been no
295   previous ``EHLO`` or ``HELO`` command this session.  It tries ESMTP ``EHLO``
296   first.
297
298   :exc:`SMTPHeloError`
299     The server didn't reply properly to the ``HELO`` greeting.
300
301.. method:: SMTP.has_extn(name)
302
303   Return :const:`True` if *name* is in the set of SMTP service extensions returned
304   by the server, :const:`False` otherwise. Case is ignored.
305
306
307.. method:: SMTP.verify(address)
308
309   Check the validity of an address on this server using SMTP ``VRFY``. Returns a
310   tuple consisting of code 250 and a full :rfc:`822` address (including human
311   name) if the user address is valid. Otherwise returns an SMTP error code of 400
312   or greater and an error string.
313
314   .. note::
315
316      Many sites disable SMTP ``VRFY`` in order to foil spammers.
317
318
319.. method:: SMTP.login(user, password, *, initial_response_ok=True)
320
321   Log in on an SMTP server that requires authentication. The arguments are the
322   username and the password to authenticate with. If there has been no previous
323   ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
324   first. This method will return normally if the authentication was successful, or
325   may raise the following exceptions:
326
327   :exc:`SMTPHeloError`
328      The server didn't reply properly to the ``HELO`` greeting.
329
330   :exc:`SMTPAuthenticationError`
331      The server didn't accept the username/password combination.
332
333   :exc:`SMTPNotSupportedError`
334      The ``AUTH`` command is not supported by the server.
335
336   :exc:`SMTPException`
337      No suitable authentication method was found.
338
339   Each of the authentication methods supported by :mod:`smtplib` are tried in
340   turn if they are advertised as supported by the server.  See :meth:`auth`
341   for a list of supported authentication methods.  *initial_response_ok* is
342   passed through to :meth:`auth`.
343
344   Optional keyword argument *initial_response_ok* specifies whether, for
345   authentication methods that support it, an "initial response" as specified
346   in :rfc:`4954` can be sent along with the ``AUTH`` command, rather than
347   requiring a challenge/response.
348
349   .. versionchanged:: 3.5
350      :exc:`SMTPNotSupportedError` may be raised, and the
351      *initial_response_ok* parameter was added.
352
353
354.. method:: SMTP.auth(mechanism, authobject, *, initial_response_ok=True)
355
356   Issue an ``SMTP`` ``AUTH`` command for the specified authentication
357   *mechanism*, and handle the challenge response via *authobject*.
358
359   *mechanism* specifies which authentication mechanism is to
360   be used as argument to the ``AUTH`` command; the valid values are
361   those listed in the ``auth`` element of :attr:`esmtp_features`.
362
363   *authobject* must be a callable object taking an optional single argument:
364
365     data = authobject(challenge=None)
366
367   If optional keyword argument *initial_response_ok* is true,
368   ``authobject()`` will be called first with no argument.  It can return the
369   :rfc:`4954` "initial response" ASCII ``str`` which will be encoded and sent with
370   the ``AUTH`` command as below.  If the ``authobject()`` does not support an
371   initial response (e.g. because it requires a challenge), it should return
372   ``None`` when called with ``challenge=None``.  If *initial_response_ok* is
373   false, then ``authobject()`` will not be called first with ``None``.
374
375   If the initial response check returns ``None``, or if *initial_response_ok* is
376   false, ``authobject()`` will be called to process the server's challenge
377   response; the *challenge* argument it is passed will be a ``bytes``.  It
378   should return ASCII ``str`` *data* that will be base64 encoded and sent to the
379   server.
380
381   The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``,
382   and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``,
383   ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively.  They all require
384   that the ``user`` and ``password`` properties of the ``SMTP`` instance are
385   set to appropriate values.
386
387   User code does not normally need to call ``auth`` directly, but can instead
388   call the :meth:`login` method, which will try each of the above mechanisms
389   in turn, in the order listed.  ``auth`` is exposed to facilitate the
390   implementation of authentication methods not (or not yet) supported
391   directly by :mod:`smtplib`.
392
393   .. versionadded:: 3.5
394
395
396.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
397
398   Put the SMTP connection in TLS (Transport Layer Security) mode.  All SMTP
399   commands that follow will be encrypted.  You should then call :meth:`ehlo`
400   again.
401
402   If *keyfile* and *certfile* are provided, they are used to create an
403   :class:`ssl.SSLContext`.
404
405   Optional *context* parameter is an :class:`ssl.SSLContext` object; This is
406   an alternative to using a keyfile and a certfile and if specified both
407   *keyfile* and *certfile* should be ``None``.
408
409   If there has been no previous ``EHLO`` or ``HELO`` command this session,
410   this method tries ESMTP ``EHLO`` first.
411
412   .. deprecated:: 3.6
413
414       *keyfile* and *certfile* are deprecated in favor of *context*.
415       Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
416       :func:`ssl.create_default_context` select the system's trusted CA
417       certificates for you.
418
419   :exc:`SMTPHeloError`
420      The server didn't reply properly to the ``HELO`` greeting.
421
422   :exc:`SMTPNotSupportedError`
423     The server does not support the STARTTLS extension.
424
425   :exc:`RuntimeError`
426     SSL/TLS support is not available to your Python interpreter.
427
428   .. versionchanged:: 3.3
429      *context* was added.
430
431   .. versionchanged:: 3.4
432      The method now supports hostname check with
433      :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
434      :data:`~ssl.HAS_SNI`).
435
436   .. versionchanged:: 3.5
437      The error raised for lack of STARTTLS support is now the
438      :exc:`SMTPNotSupportedError` subclass instead of the base
439      :exc:`SMTPException`.
440
441
442.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
443
444   Send mail.  The required arguments are an :rfc:`822` from-address string, a list
445   of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
446   address), and a message string.  The caller may pass a list of ESMTP options
447   (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
448   ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
449   commands can be passed as *rcpt_options*.  (If you need to use different ESMTP
450   options to different recipients you have to use the low-level methods such as
451   :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
452
453   .. note::
454
455      The *from_addr* and *to_addrs* parameters are used to construct the message
456      envelope used by the transport agents.  ``sendmail`` does not modify the
457      message headers in any way.
458
459   *msg* may be a string containing characters in the ASCII range, or a byte
460   string.  A string is encoded to bytes using the ascii codec, and lone ``\r``
461   and ``\n`` characters are converted to ``\r\n`` characters.  A byte string is
462   not modified.
463
464   If there has been no previous ``EHLO`` or ``HELO`` command this session, this
465   method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
466   each of the specified options will be passed to it (if the option is in the
467   feature set the server advertises).  If ``EHLO`` fails, ``HELO`` will be tried
468   and ESMTP options suppressed.
469
470   This method will return normally if the mail is accepted for at least one
471   recipient. Otherwise it will raise an exception.  That is, if this method does
472   not raise an exception, then someone should get your mail. If this method does
473   not raise an exception, it returns a dictionary, with one entry for each
474   recipient that was refused.  Each entry contains a tuple of the SMTP error code
475   and the accompanying error message sent by the server.
476
477   If ``SMTPUTF8`` is included in *mail_options*, and the server supports it,
478   *from_addr* and *to_addrs* may contain non-ASCII characters.
479
480   This method may raise the following exceptions:
481
482   :exc:`SMTPRecipientsRefused`
483      All recipients were refused.  Nobody got the mail.  The :attr:`recipients`
484      attribute of the exception object is a dictionary with information about the
485      refused recipients (like the one returned when at least one recipient was
486      accepted).
487
488   :exc:`SMTPHeloError`
489      The server didn't reply properly to the ``HELO`` greeting.
490
491   :exc:`SMTPSenderRefused`
492      The server didn't accept the *from_addr*.
493
494   :exc:`SMTPDataError`
495      The server replied with an unexpected error code (other than a refusal of a
496      recipient).
497
498   :exc:`SMTPNotSupportedError`
499      ``SMTPUTF8`` was given in the *mail_options* but is not supported by the
500      server.
501
502   Unless otherwise noted, the connection will be open even after an exception is
503   raised.
504
505   .. versionchanged:: 3.2
506      *msg* may be a byte string.
507
508   .. versionchanged:: 3.5
509      ``SMTPUTF8`` support added, and :exc:`SMTPNotSupportedError` may be
510      raised if ``SMTPUTF8`` is specified but the server does not support it.
511
512
513.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
514                              mail_options=(), rcpt_options=())
515
516   This is a convenience method for calling :meth:`sendmail` with the message
517   represented by an :class:`email.message.Message` object.  The arguments have
518   the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
519   object.
520
521   If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
522   those arguments with addresses extracted from the headers of *msg* as
523   specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender`
524   field if it is present, and otherwise to the :mailheader:`From` field.
525   *to_addrs* combines the values (if any) of the :mailheader:`To`,
526   :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*.  If exactly one
527   set of :mailheader:`Resent-*` headers appear in the message, the regular
528   headers are ignored and the :mailheader:`Resent-*` headers are used instead.
529   If the message contains more than one set of :mailheader:`Resent-*` headers,
530   a :exc:`ValueError` is raised, since there is no way to unambiguously detect
531   the most recent set of :mailheader:`Resent-` headers.
532
533   ``send_message`` serializes *msg* using
534   :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
535   calls :meth:`sendmail` to transmit the resulting message.  Regardless of the
536   values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
537   :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
538   in *msg*.  If any of the addresses in *from_addr* and *to_addrs* contain
539   non-ASCII characters and the server does not advertise ``SMTPUTF8`` support,
540   an :exc:`SMTPNotSupported` error is raised.  Otherwise the ``Message`` is
541   serialized with a clone of its :mod:`~email.policy` with the
542   :attr:`~email.policy.EmailPolicy.utf8` attribute set to ``True``, and
543   ``SMTPUTF8`` and ``BODY=8BITMIME`` are added to *mail_options*.
544
545   .. versionadded:: 3.2
546
547   .. versionadded:: 3.5
548      Support for internationalized addresses (``SMTPUTF8``).
549
550
551.. method:: SMTP.quit()
552
553   Terminate the SMTP session and close the connection.  Return the result of
554   the SMTP ``QUIT`` command.
555
556
557Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
558``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
559Normally these do not need to be called directly, so they are not documented
560here.  For details, consult the module code.
561
562
563.. _smtp-example:
564
565SMTP Example
566------------
567
568This example prompts the user for addresses needed in the message envelope ('To'
569and 'From' addresses), and the message to be delivered.  Note that the headers
570to be included with the message must be included in the message as entered; this
571example doesn't do any processing of the :rfc:`822` headers.  In particular, the
572'To' and 'From' addresses must be included in the message headers explicitly. ::
573
574   import smtplib
575
576   def prompt(prompt):
577       return input(prompt).strip()
578
579   fromaddr = prompt("From: ")
580   toaddrs  = prompt("To: ").split()
581   print("Enter message, end with ^D (Unix) or ^Z (Windows):")
582
583   # Add the From: and To: headers at the start!
584   msg = ("From: %s\r\nTo: %s\r\n\r\n"
585          % (fromaddr, ", ".join(toaddrs)))
586   while True:
587       try:
588           line = input()
589       except EOFError:
590           break
591       if not line:
592           break
593       msg = msg + line
594
595   print("Message length is", len(msg))
596
597   server = smtplib.SMTP('localhost')
598   server.set_debuglevel(1)
599   server.sendmail(fromaddr, toaddrs, msg)
600   server.quit()
601
602.. note::
603
604   In general, you will want to use the :mod:`email` package's features to
605   construct an email message, which you can then send
606   via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.
607