blob: 74de77b94eddbf21bc4010af0cb32617b00c9619 [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
192 Set the debug output level. A true value for *level* results in debug messages
193 for connection and for all messages sent to and received from the server.
194
195
Georg Brandl18244152009-09-02 20:34:52 +0000196.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Georg Brandl18244152009-09-02 20:34:52 +0000198 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000199 concatenated to the command, separated by a space.
200
201 This returns a 2-tuple composed of a numeric response code and the actual
202 response line (multiline responses are joined into one long line.)
203
204 In normal operation it should not be necessary to call this method explicitly.
205 It is used to implement other methods and may be useful for testing private
206 extensions.
207
208 If the connection to the server is lost while waiting for the reply,
209 :exc:`SMTPServerDisconnected` will be raised.
210
211
R David Murray14ee3cf2013-04-13 14:40:33 -0400212.. method:: SMTP.connect(host='localhost', port=0)
213
214 Connect to a host on a given port. The defaults are to connect to the local
215 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
216 followed by a number, that suffix will be stripped off and the number
217 interpreted as the port number to use. This method is automatically invoked by
218 the constructor if a host is specified during instantiation. Returns a
219 2-tuple of the response code and message sent by the server in its
220 connection response.
221
222
Georg Brandl18244152009-09-02 20:34:52 +0000223.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225 Identify yourself to the SMTP server using ``HELO``. The hostname argument
226 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000227 The message returned by the server is stored as the :attr:`helo_resp` attribute
228 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 In normal operation it should not be necessary to call this method explicitly.
231 It will be implicitly called by the :meth:`sendmail` when necessary.
232
233
Georg Brandl18244152009-09-02 20:34:52 +0000234.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
237 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000238 response for ESMTP option and store them for use by :meth:`has_extn`.
239 Also sets several informational attributes: the message returned by
240 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000241 is set to true or false depending on whether the server supports ESMTP, and
242 :attr:`esmtp_features` will be a dictionary containing the names of the
R David Murray76e13c12014-07-03 14:47:46 -0400243 SMTP service extensions this server supports, and their parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
246 necessary to call this method explicitly. It will be implicitly called by
247 :meth:`sendmail` when necessary.
248
Christian Heimes679db4a2008-01-18 09:56:22 +0000249.. method:: SMTP.ehlo_or_helo_if_needed()
250
251 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
252 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
253 first.
254
Georg Brandl1f01deb2009-01-03 22:47:39 +0000255 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000256 The server didn't reply properly to the ``HELO`` greeting.
257
Georg Brandl116aa622007-08-15 14:28:22 +0000258.. method:: SMTP.has_extn(name)
259
260 Return :const:`True` if *name* is in the set of SMTP service extensions returned
261 by the server, :const:`False` otherwise. Case is ignored.
262
263
264.. method:: SMTP.verify(address)
265
266 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
267 tuple consisting of code 250 and a full :rfc:`822` address (including human
268 name) if the user address is valid. Otherwise returns an SMTP error code of 400
269 or greater and an error string.
270
271 .. note::
272
273 Many sites disable SMTP ``VRFY`` in order to foil spammers.
274
275
276.. method:: SMTP.login(user, password)
277
278 Log in on an SMTP server that requires authentication. The arguments are the
279 username and the password to authenticate with. If there has been no previous
280 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
281 first. This method will return normally if the authentication was successful, or
282 may raise the following exceptions:
283
284 :exc:`SMTPHeloError`
285 The server didn't reply properly to the ``HELO`` greeting.
286
287 :exc:`SMTPAuthenticationError`
288 The server didn't accept the username/password combination.
289
290 :exc:`SMTPException`
291 No suitable authentication method was found.
292
R David Murray76e13c12014-07-03 14:47:46 -0400293 Each of the authentication methods supported by :mod:`smtplib` are tried in
294 turn if they are advertised as supported by the server (see :meth:`auth`
295 for a list of supported authentication methods).
296
297
298.. method:: SMTP.auth(mechanism, authobject)
299
300 Issue an ``SMTP`` ``AUTH`` command for the specified authentication
301 *mechanism*, and handle the challenge response via *authobject*.
302
303 *mechanism* specifies which authentication mechanism is to
304 be used as argument to the ``AUTH`` command; the valid values are
305 those listed in the ``auth`` element of :attr:`esmtp_features`.
306
307 *authobject* must be a callable object taking a single argument:
308
309 data = authobject(challenge)
310
311 It will be called to process the server's challenge response; the
312 *challenge* argument it is passed will be a ``bytes``. It should return
313 ``bytes`` *data* that will be base64 encoded and sent to the server.
314
315 The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``,
316 and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``,
317 ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively. They all require
318 that the ``user`` and ``password`` properties of the ``SMTP`` instance are
319 set to appropriate values.
320
321 User code does not normally need to call ``auth`` directly, but can instead
322 call the :meth:`login` method, which will try each of the above mechanisms in
323 turn, in the order listed. ``auth`` is exposed to facilitate the
324 implementation of authentication methods not (or not yet) supported directly
325 by :mod:`smtplib`.
326
327 .. versionadded:: 3.5
328
Georg Brandl116aa622007-08-15 14:28:22 +0000329
Antoine Pitroue0650202011-05-18 18:03:09 +0200330.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
333 commands that follow will be encrypted. You should then call :meth:`ehlo`
334 again.
335
336 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
337 module's :func:`ssl` function.
338
Antoine Pitroue0650202011-05-18 18:03:09 +0200339 Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
340 using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
341
Christian Heimes679db4a2008-01-18 09:56:22 +0000342 If there has been no previous ``EHLO`` or ``HELO`` command this session,
343 this method tries ESMTP ``EHLO`` first.
344
Christian Heimes679db4a2008-01-18 09:56:22 +0000345 :exc:`SMTPHeloError`
346 The server didn't reply properly to the ``HELO`` greeting.
347
348 :exc:`SMTPException`
349 The server does not support the STARTTLS extension.
350
Christian Heimes679db4a2008-01-18 09:56:22 +0000351 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000352 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000353
Antoine Pitroue0650202011-05-18 18:03:09 +0200354 .. versionchanged:: 3.3
355 *context* was added.
356
Christian Heimesa5768f72013-12-02 20:44:17 +0100357 .. versionchanged:: 3.4
358 The method now supports hostname check with
359 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
360 :data:`~ssl.HAS_SNI`).
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl18244152009-09-02 20:34:52 +0000363.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365 Send mail. The required arguments are an :rfc:`822` from-address string, a list
366 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
367 address), and a message string. The caller may pass a list of ESMTP options
368 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
369 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
370 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
371 options to different recipients you have to use the low-level methods such as
372 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
373
374 .. note::
375
376 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000377 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000378 message headers in any way.
379
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600380 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000381 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600382 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
383 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000384
Georg Brandl116aa622007-08-15 14:28:22 +0000385 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
386 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
387 each of the specified options will be passed to it (if the option is in the
388 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
389 and ESMTP options suppressed.
390
391 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000392 recipient. Otherwise it will raise an exception. That is, if this method does
393 not raise an exception, then someone should get your mail. If this method does
394 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000395 recipient that was refused. Each entry contains a tuple of the SMTP error code
396 and the accompanying error message sent by the server.
397
398 This method may raise the following exceptions:
399
400 :exc:`SMTPRecipientsRefused`
401 All recipients were refused. Nobody got the mail. The :attr:`recipients`
402 attribute of the exception object is a dictionary with information about the
403 refused recipients (like the one returned when at least one recipient was
404 accepted).
405
406 :exc:`SMTPHeloError`
407 The server didn't reply properly to the ``HELO`` greeting.
408
409 :exc:`SMTPSenderRefused`
410 The server didn't accept the *from_addr*.
411
412 :exc:`SMTPDataError`
413 The server replied with an unexpected error code (other than a refusal of a
414 recipient).
415
416 Unless otherwise noted, the connection will be open even after an exception is
417 raised.
418
Georg Brandl61063cc2012-06-24 22:48:30 +0200419 .. versionchanged:: 3.2
420 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000421
422
R David Murrayac4e5ab2011-07-02 21:03:19 -0400423.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
424 mail_options=[], rcpt_options=[])
R. David Murray7dff9e02010-11-08 17:15:13 +0000425
426 This is a convenience method for calling :meth:`sendmail` with the message
427 represented by an :class:`email.message.Message` object. The arguments have
428 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
429 object.
430
R David Murrayac4e5ab2011-07-02 21:03:19 -0400431 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
432 those arguments with addresses extracted from the headers of *msg* as
433 specified in :rfc:`2822`\: *from_addr* is set to the :mailheader:`Sender`
434 field if it is present, and otherwise to the :mailheader:`From` field.
435 *to_adresses* combines the values (if any) of the :mailheader:`To`,
436 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
437 set of :mailheader:`Resent-*` headers appear in the message, the regular
438 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
439 If the message contains more than one set of :mailheader:`Resent-*` headers,
440 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
441 the most recent set of :mailheader:`Resent-` headers.
442
443 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000444 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400445 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
446 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
447 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
448 in *msg*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000449
450 .. versionadded:: 3.2
451
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453.. method:: SMTP.quit()
454
Christian Heimesba4af492008-03-28 00:55:15 +0000455 Terminate the SMTP session and close the connection. Return the result of
456 the SMTP ``QUIT`` command.
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
460``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
461Normally these do not need to be called directly, so they are not documented
462here. For details, consult the module code.
463
464
465.. _smtp-example:
466
467SMTP Example
468------------
469
470This example prompts the user for addresses needed in the message envelope ('To'
471and 'From' addresses), and the message to be delivered. Note that the headers
472to be included with the message must be included in the message as entered; this
473example doesn't do any processing of the :rfc:`822` headers. In particular, the
474'To' and 'From' addresses must be included in the message headers explicitly. ::
475
476 import smtplib
477
Georg Brandl116aa622007-08-15 14:28:22 +0000478 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000479 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481 fromaddr = prompt("From: ")
482 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000483 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485 # Add the From: and To: headers at the start!
486 msg = ("From: %s\r\nTo: %s\r\n\r\n"
487 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000488 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000489 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000490 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000491 except EOFError:
492 break
493 if not line:
494 break
495 msg = msg + line
496
Georg Brandl6911e3c2007-09-04 07:15:32 +0000497 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499 server = smtplib.SMTP('localhost')
500 server.set_debuglevel(1)
501 server.sendmail(fromaddr, toaddrs, msg)
502 server.quit()
503
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000504.. note::
505
506 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000507 construct an email message, which you can then send
508 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.