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