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