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