blob: 44473fe65bf99c74fa39290dad2b10fb3171542a [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`smtplib` --- SMTP protocol client
2=======================================
3
4.. module:: smtplib
5 :synopsis: SMTP protocol client (requires sockets).
6.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
7
8
9.. index::
10 pair: SMTP; protocol
11 single: Simple Mail Transfer Protocol
12
Raymond Hettinger469271d2011-01-27 20:38:46 +000013**Source code:** :source:`Lib/smtplib.py`
14
15--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +000017The :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
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080023.. class:: SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000024
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000025 A :class:`SMTP` instance encapsulates an SMTP connection. It has methods
26 that support a full repertoire of SMTP and ESMTP operations. If the optional
R David Murray021362d2013-06-23 16:05:44 -040027 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
R David Murray6ceca4e2014-06-09 16:41:06 -040035 setting will be used). If the timeout expires, :exc:`socket.timeout` is
36 raised. The optional source_address parameter allows to bind
R David Murray021362d2013-06-23 16:05:44 -040037 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.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 For normal use, you should only require the initialization/connect,
Jesus Ceac73f8632012-12-26 16:47:03 +010044 :meth:`sendmail`, and :meth:`~smtplib.quit` methods.
45 An example is included below.
Georg Brandl116aa622007-08-15 14:28:22 +000046
Barry Warsaw1f5c9582011-03-15 15:04:44 -040047 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
Antoine Pitrou45456a02011-04-26 18:53:42 +020058 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040059 Support for the :keyword:`with` statement was added.
60
Senthil Kumaranb351a482011-07-31 09:14:17 +080061 .. versionchanged:: 3.3
62 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000063
R David Murray36beb662013-06-23 15:47:50 -040064.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \
65 certfile=None [, timeout], context=None, \
66 source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
69 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000070 required from the beginning of the connection and using :meth:`starttls` is
71 not appropriate. If *host* is not specified, the local host is used. If
R David Murray36beb662013-06-23 15:47:50 -040072 *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010073 arguments *local_hostname*, *timeout* and *source_address* have the same
74 meaning as they do in the :class:`SMTP` class. *context*, also optional,
75 can contain a :class:`~ssl.SSLContext` and allows to configure various
76 aspects of the secure connection. Please read :ref:`ssl-security` for
77 best practices.
78
79 *keyfile* and *certfile* are a legacy alternative to *context*, and can
80 point to a PEM formatted private key and certificate chain file for the
81 SSL connection.
Georg Brandl116aa622007-08-15 14:28:22 +000082
Antoine Pitroue0650202011-05-18 18:03:09 +020083 .. versionchanged:: 3.3
84 *context* was added.
85
Senthil Kumaranb351a482011-07-31 09:14:17 +080086 .. versionchanged:: 3.3
87 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000088
Christian Heimesa5768f72013-12-02 20:44:17 +010089 .. versionchanged:: 3.4
90 The class now supports hostname check with
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010091 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
92 :data:`ssl.HAS_SNI`).
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080093
94.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000095
96 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080097 standard SMTP client. It's common to use Unix sockets for LMTP, so our
98 :meth:`connect` method must support that as well as a regular host:port
Senthil Kumaranb351a482011-07-31 09:14:17 +080099 server. The optional arguments local_hostname and source_address have the
R David Murray021362d2013-06-23 16:05:44 -0400100 same meaning as they do in the :class:`SMTP` class. To specify a Unix
101 socket, you must use an absolute path for *host*, starting with a '/'.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
R David Murray021362d2013-06-23 16:05:44 -0400103 Authentication is supported, using the regular SMTP mechanism. When using a
104 Unix socket, LMTP generally don't support or require any authentication, but
105 your mileage might vary.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108A nice selection of exceptions is defined as well:
109
110
111.. exception:: SMTPException
112
R David Murray8a345962013-04-14 06:46:35 -0400113 Subclass of :exc:`OSError` that is the base exception class for all
Ned Deily7cf5e612013-08-13 01:15:14 -0700114 the other exceptions provided by this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Larry Hastings3732ed22014-03-15 21:13:56 -0700116 .. versionchanged:: 3.4
117 SMTPException became subclass of :exc:`OSError`
118
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120.. exception:: SMTPServerDisconnected
121
122 This exception is raised when the server unexpectedly disconnects, or when an
123 attempt is made to use the :class:`SMTP` instance before connecting it to a
124 server.
125
126
127.. exception:: SMTPResponseException
128
129 Base class for all exceptions that include an SMTP error code. These exceptions
130 are generated in some instances when the SMTP server returns an error code. The
131 error code is stored in the :attr:`smtp_code` attribute of the error, and the
132 :attr:`smtp_error` attribute is set to the error message.
133
134
135.. exception:: SMTPSenderRefused
136
137 Sender address refused. In addition to the attributes set by on all
138 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
139 the SMTP server refused.
140
141
142.. exception:: SMTPRecipientsRefused
143
144 All recipient addresses refused. The errors for each recipient are accessible
145 through the attribute :attr:`recipients`, which is a dictionary of exactly the
146 same sort as :meth:`SMTP.sendmail` returns.
147
148
149.. exception:: SMTPDataError
150
151 The SMTP server refused to accept the message data.
152
153
154.. exception:: SMTPConnectError
155
156 Error occurred during establishment of a connection with the server.
157
158
159.. exception:: SMTPHeloError
160
161 The server refused our ``HELO`` message.
162
163
164.. exception:: SMTPAuthenticationError
165
166 SMTP authentication went wrong. Most probably the server didn't accept the
167 username/password combination provided.
168
169
170.. seealso::
171
172 :rfc:`821` - Simple Mail Transfer Protocol
173 Protocol definition for SMTP. This document covers the model, operating
174 procedure, and protocol details for SMTP.
175
176 :rfc:`1869` - SMTP Service Extensions
177 Definition of the ESMTP extensions for SMTP. This describes a framework for
178 extending SMTP with new commands, supporting dynamic discovery of the commands
179 provided by the server, and defines a few additional commands.
180
181
182.. _smtp-objects:
183
184SMTP Objects
185------------
186
187An :class:`SMTP` instance has the following methods:
188
189
190.. method:: SMTP.set_debuglevel(level)
191
R David Murray2e6ad422015-04-16 17:24:52 -0400192 Set the debug output level. A value of 1 or ``True`` for *level* results in
193 debug messages for connection and for all messages sent to and received from
194 the server. A value of 2 for *level* results in these messages being
195 timestamped.
196
197 .. versionchanged:: 3.5 Added debuglevel 2.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
Georg Brandl18244152009-09-02 20:34:52 +0000200.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Georg Brandl18244152009-09-02 20:34:52 +0000202 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000203 concatenated to the command, separated by a space.
204
205 This returns a 2-tuple composed of a numeric response code and the actual
206 response line (multiline responses are joined into one long line.)
207
208 In normal operation it should not be necessary to call this method explicitly.
209 It is used to implement other methods and may be useful for testing private
210 extensions.
211
212 If the connection to the server is lost while waiting for the reply,
213 :exc:`SMTPServerDisconnected` will be raised.
214
215
R David Murray14ee3cf2013-04-13 14:40:33 -0400216.. method:: SMTP.connect(host='localhost', port=0)
217
218 Connect to a host on a given port. The defaults are to connect to the local
219 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
220 followed by a number, that suffix will be stripped off and the number
221 interpreted as the port number to use. This method is automatically invoked by
222 the constructor if a host is specified during instantiation. Returns a
223 2-tuple of the response code and message sent by the server in its
224 connection response.
225
226
Georg Brandl18244152009-09-02 20:34:52 +0000227.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229 Identify yourself to the SMTP server using ``HELO``. The hostname argument
230 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000231 The message returned by the server is stored as the :attr:`helo_resp` attribute
232 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234 In normal operation it should not be necessary to call this method explicitly.
235 It will be implicitly called by the :meth:`sendmail` when necessary.
236
237
Georg Brandl18244152009-09-02 20:34:52 +0000238.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
241 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000242 response for ESMTP option and store them for use by :meth:`has_extn`.
243 Also sets several informational attributes: the message returned by
244 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000245 is set to true or false depending on whether the server supports ESMTP, and
246 :attr:`esmtp_features` will be a dictionary containing the names of the
R David Murray76e13c12014-07-03 14:47:46 -0400247 SMTP service extensions this server supports, and their parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
250 necessary to call this method explicitly. It will be implicitly called by
251 :meth:`sendmail` when necessary.
252
Christian Heimes679db4a2008-01-18 09:56:22 +0000253.. method:: SMTP.ehlo_or_helo_if_needed()
254
255 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
256 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
257 first.
258
Georg Brandl1f01deb2009-01-03 22:47:39 +0000259 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000260 The server didn't reply properly to the ``HELO`` greeting.
261
Georg Brandl116aa622007-08-15 14:28:22 +0000262.. method:: SMTP.has_extn(name)
263
264 Return :const:`True` if *name* is in the set of SMTP service extensions returned
265 by the server, :const:`False` otherwise. Case is ignored.
266
267
268.. method:: SMTP.verify(address)
269
270 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
271 tuple consisting of code 250 and a full :rfc:`822` address (including human
272 name) if the user address is valid. Otherwise returns an SMTP error code of 400
273 or greater and an error string.
274
275 .. note::
276
277 Many sites disable SMTP ``VRFY`` in order to foil spammers.
278
279
280.. method:: SMTP.login(user, password)
281
282 Log in on an SMTP server that requires authentication. The arguments are the
283 username and the password to authenticate with. If there has been no previous
284 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
285 first. This method will return normally if the authentication was successful, or
286 may raise the following exceptions:
287
288 :exc:`SMTPHeloError`
289 The server didn't reply properly to the ``HELO`` greeting.
290
291 :exc:`SMTPAuthenticationError`
292 The server didn't accept the username/password combination.
293
294 :exc:`SMTPException`
295 No suitable authentication method was found.
296
R David Murray76e13c12014-07-03 14:47:46 -0400297 Each of the authentication methods supported by :mod:`smtplib` are tried in
298 turn if they are advertised as supported by the server (see :meth:`auth`
299 for a list of supported authentication methods).
300
301
302.. method:: SMTP.auth(mechanism, authobject)
303
304 Issue an ``SMTP`` ``AUTH`` command for the specified authentication
305 *mechanism*, and handle the challenge response via *authobject*.
306
307 *mechanism* specifies which authentication mechanism is to
308 be used as argument to the ``AUTH`` command; the valid values are
309 those listed in the ``auth`` element of :attr:`esmtp_features`.
310
311 *authobject* must be a callable object taking a single argument:
312
313 data = authobject(challenge)
314
315 It will be called to process the server's challenge response; the
316 *challenge* argument it is passed will be a ``bytes``. It should return
317 ``bytes`` *data* that will be base64 encoded and sent to the server.
318
319 The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``,
320 and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``,
321 ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively. They all require
322 that the ``user`` and ``password`` properties of the ``SMTP`` instance are
323 set to appropriate values.
324
325 User code does not normally need to call ``auth`` directly, but can instead
326 call the :meth:`login` method, which will try each of the above mechanisms in
327 turn, in the order listed. ``auth`` is exposed to facilitate the
328 implementation of authentication methods not (or not yet) supported directly
329 by :mod:`smtplib`.
330
331 .. versionadded:: 3.5
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Antoine Pitroue0650202011-05-18 18:03:09 +0200334.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
337 commands that follow will be encrypted. You should then call :meth:`ehlo`
338 again.
339
340 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
341 module's :func:`ssl` function.
342
Antoine Pitroue0650202011-05-18 18:03:09 +0200343 Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
344 using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
345
Christian Heimes679db4a2008-01-18 09:56:22 +0000346 If there has been no previous ``EHLO`` or ``HELO`` command this session,
347 this method tries ESMTP ``EHLO`` first.
348
Christian Heimes679db4a2008-01-18 09:56:22 +0000349 :exc:`SMTPHeloError`
350 The server didn't reply properly to the ``HELO`` greeting.
351
352 :exc:`SMTPException`
353 The server does not support the STARTTLS extension.
354
Christian Heimes679db4a2008-01-18 09:56:22 +0000355 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000356 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000357
Antoine Pitroue0650202011-05-18 18:03:09 +0200358 .. versionchanged:: 3.3
359 *context* was added.
360
Christian Heimesa5768f72013-12-02 20:44:17 +0100361 .. versionchanged:: 3.4
362 The method now supports hostname check with
363 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
364 :data:`~ssl.HAS_SNI`).
365
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Georg Brandl18244152009-09-02 20:34:52 +0000367.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369 Send mail. The required arguments are an :rfc:`822` from-address string, a list
370 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
371 address), and a message string. The caller may pass a list of ESMTP options
372 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
373 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
374 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
375 options to different recipients you have to use the low-level methods such as
376 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
377
378 .. note::
379
380 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000381 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000382 message headers in any way.
383
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600384 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000385 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600386 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
387 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000388
Georg Brandl116aa622007-08-15 14:28:22 +0000389 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
390 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
391 each of the specified options will be passed to it (if the option is in the
392 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
393 and ESMTP options suppressed.
394
395 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000396 recipient. Otherwise it will raise an exception. That is, if this method does
397 not raise an exception, then someone should get your mail. If this method does
398 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000399 recipient that was refused. Each entry contains a tuple of the SMTP error code
400 and the accompanying error message sent by the server.
401
402 This method may raise the following exceptions:
403
404 :exc:`SMTPRecipientsRefused`
405 All recipients were refused. Nobody got the mail. The :attr:`recipients`
406 attribute of the exception object is a dictionary with information about the
407 refused recipients (like the one returned when at least one recipient was
408 accepted).
409
410 :exc:`SMTPHeloError`
411 The server didn't reply properly to the ``HELO`` greeting.
412
413 :exc:`SMTPSenderRefused`
414 The server didn't accept the *from_addr*.
415
416 :exc:`SMTPDataError`
417 The server replied with an unexpected error code (other than a refusal of a
418 recipient).
419
420 Unless otherwise noted, the connection will be open even after an exception is
421 raised.
422
Georg Brandl61063cc2012-06-24 22:48:30 +0200423 .. versionchanged:: 3.2
424 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000425
426
R David Murrayac4e5ab2011-07-02 21:03:19 -0400427.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
428 mail_options=[], rcpt_options=[])
R. David Murray7dff9e02010-11-08 17:15:13 +0000429
430 This is a convenience method for calling :meth:`sendmail` with the message
431 represented by an :class:`email.message.Message` object. The arguments have
432 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
433 object.
434
R David Murrayac4e5ab2011-07-02 21:03:19 -0400435 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
436 those arguments with addresses extracted from the headers of *msg* as
437 specified in :rfc:`2822`\: *from_addr* is set to the :mailheader:`Sender`
438 field if it is present, and otherwise to the :mailheader:`From` field.
439 *to_adresses* combines the values (if any) of the :mailheader:`To`,
440 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
441 set of :mailheader:`Resent-*` headers appear in the message, the regular
442 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
443 If the message contains more than one set of :mailheader:`Resent-*` headers,
444 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
445 the most recent set of :mailheader:`Resent-` headers.
446
447 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000448 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400449 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
450 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
451 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
452 in *msg*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000453
454 .. versionadded:: 3.2
455
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457.. method:: SMTP.quit()
458
Christian Heimesba4af492008-03-28 00:55:15 +0000459 Terminate the SMTP session and close the connection. Return the result of
460 the SMTP ``QUIT`` command.
461
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
464``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
465Normally these do not need to be called directly, so they are not documented
466here. For details, consult the module code.
467
468
469.. _smtp-example:
470
471SMTP Example
472------------
473
474This example prompts the user for addresses needed in the message envelope ('To'
475and 'From' addresses), and the message to be delivered. Note that the headers
476to be included with the message must be included in the message as entered; this
477example doesn't do any processing of the :rfc:`822` headers. In particular, the
478'To' and 'From' addresses must be included in the message headers explicitly. ::
479
480 import smtplib
481
Georg Brandl116aa622007-08-15 14:28:22 +0000482 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000483 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485 fromaddr = prompt("From: ")
486 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000487 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489 # Add the From: and To: headers at the start!
490 msg = ("From: %s\r\nTo: %s\r\n\r\n"
491 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000492 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000493 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000494 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000495 except EOFError:
496 break
497 if not line:
498 break
499 msg = msg + line
500
Georg Brandl6911e3c2007-09-04 07:15:32 +0000501 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503 server = smtplib.SMTP('localhost')
504 server.set_debuglevel(1)
505 server.sendmail(fromaddr, toaddrs, msg)
506 server.quit()
507
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000508.. note::
509
510 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000511 construct an email message, which you can then send
512 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.