Debian Codegraph @

Doc/library/smtplib.rst

raw
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
17 The :mod:`!smtplib` module defines an SMTP client session object that can be used
18 to send mail to any internet machine with an SMTP or ESMTP listener daemon. For
19 details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
20 Protocol) 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:`~SMTP.starttls`
84 is 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:`~SMTP.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
128 A 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.
151
152 .. attribute:: smtp_code
153
154 The error code.
155
156 .. attribute:: smtp_error
157
158 The error message.
159
160
161 .. exception:: SMTPSenderRefused
162
163 Sender address refused. In addition to the attributes set by on all
164 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
165 the SMTP server refused.
166
167
168 .. exception:: SMTPRecipientsRefused
169
170 All recipient addresses refused.
171
172 .. attribute:: recipients
173
174 A dictionary of exactly the same sort as returned
175 by :meth:`SMTP.sendmail` containing the errors for
176 each recipient.
177
178
179 .. exception:: SMTPDataError
180
181 The SMTP server refused to accept the message data.
182
183
184 .. exception:: SMTPConnectError
185
186 Error occurred during establishment of a connection with the server.
187
188
189 .. exception:: SMTPHeloError
190
191 The server refused our ``HELO`` message.
192
193
194 .. exception:: SMTPNotSupportedError
195
196 The command or option attempted is not supported by the server.
197
198 .. versionadded:: 3.5
199
200
201 .. exception:: SMTPAuthenticationError
202
203 SMTP authentication went wrong. Most probably the server didn't accept the
204 username/password combination provided.
205
206
207 .. seealso::
208
209 :rfc:`821` - Simple Mail Transfer Protocol
210 Protocol definition for SMTP. This document covers the model, operating
211 procedure, and protocol details for SMTP.
212
213 :rfc:`1869` - SMTP Service Extensions
214 Definition of the ESMTP extensions for SMTP. This describes a framework for
215 extending SMTP with new commands, supporting dynamic discovery of the commands
216 provided by the server, and defines a few additional commands.
217
218
219 .. _smtp-objects:
220
221 SMTP Objects
222 ------------
223
224 An :class:`SMTP` instance has the following methods:
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(*, 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 .. versionchanged:: 3.12
413 The deprecated *keyfile* and *certfile* parameters have been removed.
414
415 :exc:`SMTPHeloError`
416 The server didn't reply properly to the ``HELO`` greeting.
417
418 :exc:`SMTPNotSupportedError`
419 The server does not support the STARTTLS extension.
420
421 :exc:`RuntimeError`
422 SSL/TLS support is not available to your Python interpreter.
423
424 .. versionchanged:: 3.3
425 *context* was added.
426
427 .. versionchanged:: 3.4
428 The method now supports hostname check with
429 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indicator* (see
430 :const:`~ssl.HAS_SNI`).
431
432 .. versionchanged:: 3.5
433 The error raised for lack of STARTTLS support is now the
434 :exc:`SMTPNotSupportedError` subclass instead of the base
435 :exc:`SMTPException`.
436
437
438 .. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
439
440 Send mail. The required arguments are an :rfc:`822` from-address string, a list
441 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
442 address), and a message string. The caller may pass a list of ESMTP options
443 (such as ``"8bitmime"``) to be used in ``MAIL FROM`` commands as *mail_options*.
444 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
445 commands can be passed as *rcpt_options*. Each option should be passed as a string
446 containing the full text of the option, including any potential key
447 (for instance, ``"NOTIFY=SUCCESS,FAILURE"``). (If you need to use different ESMTP
448 options to different recipients you have to use the low-level methods such as
449 :meth:`!mail`, :meth:`!rcpt` and :meth:`!data` to send the message.)
450
451 .. note::
452
453 The *from_addr* and *to_addrs* parameters are used to construct the message
454 envelope used by the transport agents. ``sendmail`` does not modify the
455 message headers in any way.
456
457 *msg* may be a string containing characters in the ASCII range, or a byte
458 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
459 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
460 not modified.
461
462 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
463 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
464 each of the specified options will be passed to it (if the option is in the
465 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
466 and ESMTP options suppressed.
467
468 This method will return normally if the mail is accepted for at least one
469 recipient. Otherwise it will raise an exception. That is, if this method does
470 not raise an exception, then someone should get your mail. If this method does
471 not raise an exception, it returns a dictionary, with one entry for each
472 recipient that was refused. Each entry contains a tuple of the SMTP error code
473 and the accompanying error message sent by the server.
474
475 If ``SMTPUTF8`` is included in *mail_options*, and the server supports it,
476 *from_addr* and *to_addrs* may contain non-ASCII characters.
477
478 This method may raise the following exceptions:
479
480 :exc:`SMTPRecipientsRefused`
481 All recipients were refused. Nobody got the mail.
482
483 :exc:`SMTPHeloError`
484 The server didn't reply properly to the ``HELO`` greeting.
485
486 :exc:`SMTPSenderRefused`
487 The server didn't accept the *from_addr*.
488
489 :exc:`SMTPDataError`
490 The server replied with an unexpected error code (other than a refusal of a
491 recipient).
492
493 :exc:`SMTPNotSupportedError`
494 ``SMTPUTF8`` was given in the *mail_options* but is not supported by the
495 server.
496
497 Unless otherwise noted, the connection will be open even after an exception is
498 raised.
499
500 .. versionchanged:: 3.2
501 *msg* may be a byte string.
502
503 .. versionchanged:: 3.5
504 ``SMTPUTF8`` support added, and :exc:`SMTPNotSupportedError` may be
505 raised if ``SMTPUTF8`` is specified but the server does not support it.
506
507
508 .. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
509 mail_options=(), rcpt_options=())
510
511 This is a convenience method for calling :meth:`sendmail` with the message
512 represented by an :class:`email.message.Message` object. The arguments have
513 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
514 object.
515
516 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
517 those arguments with addresses extracted from the headers of *msg* as
518 specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender`
519 field if it is present, and otherwise to the :mailheader:`From` field.
520 *to_addrs* combines the values (if any) of the :mailheader:`To`,
521 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
522 set of :mailheader:`Resent-*` headers appear in the message, the regular
523 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
524 If the message contains more than one set of :mailheader:`Resent-*` headers,
525 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
526 the most recent set of :mailheader:`Resent-` headers.
527
528 ``send_message`` serializes *msg* using
529 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
530 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
531 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
532 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
533 in *msg*. If any of the addresses in *from_addr* and *to_addrs* contain
534 non-ASCII characters and the server does not advertise ``SMTPUTF8`` support,
535 an :exc:`SMTPNotSupportedError` is raised. Otherwise the ``Message`` is
536 serialized with a clone of its :mod:`~email.policy` with the
537 :attr:`~email.policy.EmailPolicy.utf8` attribute set to ``True``, and
538 ``SMTPUTF8`` and ``BODY=8BITMIME`` are added to *mail_options*.
539
540 .. versionadded:: 3.2
541
542 .. versionadded:: 3.5
543 Support for internationalized addresses (``SMTPUTF8``).
544
545
546 .. method:: SMTP.quit()
547
548 Terminate the SMTP session and close the connection. Return the result of
549 the SMTP ``QUIT`` command.
550
551
552 Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
553 ``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
554 Normally these do not need to be called directly, so they are not documented
555 here. For details, consult the module code.
556
557 Additionally, an SMTP instance has the following attributes:
558
559
560 .. attribute:: SMTP.helo_resp
561
562 The response to the ``HELO`` command, see :meth:`helo`.
563
564
565 .. attribute:: SMTP.ehlo_resp
566
567 The response to the ``EHLO`` command, see :meth:`ehlo`.
568
569
570 .. attribute:: SMTP.does_esmtp
571
572 A boolean value indicating whether the server supports ESMTP, see
573 :meth:`ehlo`.
574
575
576 .. attribute:: SMTP.esmtp_features
577
578 A dictionary of the names of SMTP service extensions supported by the server,
579 see :meth:`ehlo`.
580
581
582 .. _smtp-example:
583
584 SMTP Example
585 ------------
586
587 This example prompts the user for addresses needed in the message envelope ('To'
588 and 'From' addresses), and the message to be delivered. Note that the headers
589 to be included with the message must be included in the message as entered; this
590 example doesn't do any processing of the :rfc:`822` headers. In particular, the
591 'To' and 'From' addresses must be included in the message headers explicitly::
592
593 import smtplib
594
595 def prompt(title):
596 return input(title).strip()
597
598 from_addr = prompt("From: ")
599 to_addrs = prompt("To: ").split()
600 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
601
602 # Add the From: and To: headers at the start!
603 lines = [f"From: {from_addr}", f"To: {', '.join(to_addrs)}", ""]
604 while True:
605 try:
606 line = input()
607 except EOFError:
608 break
609 else:
610 lines.append(line)
611
612 msg = "\r\n".join(lines)
613 print("Message length is", len(msg))
614
615 server = smtplib.SMTP("localhost")
616 server.set_debuglevel(1)
617 server.sendmail(from_addr, to_addrs, msg)
618 server.quit()
619
620 .. note::
621
622 In general, you will want to use the :mod:`email` package's features to
623 construct an email message, which you can then send
624 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.