blob: a7d15384d09c33a5550e22ca8ad7a58124553205 [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
35 setting will be used). The optional source_address parameter allows to bind
36 to some specific source address in a machine with multiple network
37 interfaces, and/or to some specific source TCP port. It takes a 2-tuple
38 (host, port), for the socket to bind to as its source address before
39 connecting. If omitted (or if host or port are ``''`` and/or 0 respectively)
40 the OS default behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 For normal use, you should only require the initialization/connect,
Jesus Ceac73f8632012-12-26 16:47:03 +010043 :meth:`sendmail`, and :meth:`~smtplib.quit` methods.
44 An example is included below.
Georg Brandl116aa622007-08-15 14:28:22 +000045
Barry Warsaw1f5c9582011-03-15 15:04:44 -040046 The :class:`SMTP` class supports the :keyword:`with` statement. When used
47 like this, the SMTP ``QUIT`` command is issued automatically when the
48 :keyword:`with` statement exits. E.g.::
49
50 >>> from smtplib import SMTP
51 >>> with SMTP("domain.org") as smtp:
52 ... smtp.noop()
53 ...
54 (250, b'Ok')
55 >>>
56
Antoine Pitrou45456a02011-04-26 18:53:42 +020057 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040058 Support for the :keyword:`with` statement was added.
59
Senthil Kumaranb351a482011-07-31 09:14:17 +080060 .. versionchanged:: 3.3
61 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000062
R David Murray36beb662013-06-23 15:47:50 -040063.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \
64 certfile=None [, timeout], context=None, \
65 source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
68 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000069 required from the beginning of the connection and using :meth:`starttls` is
70 not appropriate. If *host* is not specified, the local host is used. If
R David Murray36beb662013-06-23 15:47:50 -040071 *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional
72 arguments *local_hostname* and *source_address* have the same meaning as
R David Murray021362d2013-06-23 16:05:44 -040073 they do in the :class:`SMTP` class. *keyfile* and *certfile* are also
74 optional, and can contain a PEM formatted private key and certificate chain
75 file for the SSL connection. *context* also optional, can contain a
76 SSLContext, and is an alternative to keyfile and certfile; If it is
77 specified both keyfile and certfile must be None. The optional *timeout*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000078 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000079 connection attempt (if not specified, the global default timeout setting
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080080 will be used). The optional source_address parameter allows to bind to some
81 specific source address in a machine with multiple network interfaces,
82 and/or to some specific source tcp port. It takes a 2-tuple (host, port),
83 for the socket to bind to as its source address before connecting. If
Senthil Kumaranb351a482011-07-31 09:14:17 +080084 omitted (or if host or port are ``''`` and/or 0 respectively) the OS default
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080085 behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000086
Antoine Pitroue0650202011-05-18 18:03:09 +020087 .. versionchanged:: 3.3
88 *context* was added.
89
Senthil Kumaranb351a482011-07-31 09:14:17 +080090 .. versionchanged:: 3.3
91 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000092
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
116
117.. exception:: SMTPServerDisconnected
118
119 This exception is raised when the server unexpectedly disconnects, or when an
120 attempt is made to use the :class:`SMTP` instance before connecting it to a
121 server.
122
123
124.. exception:: SMTPResponseException
125
126 Base class for all exceptions that include an SMTP error code. These exceptions
127 are generated in some instances when the SMTP server returns an error code. The
128 error code is stored in the :attr:`smtp_code` attribute of the error, and the
129 :attr:`smtp_error` attribute is set to the error message.
130
131
132.. exception:: SMTPSenderRefused
133
134 Sender address refused. In addition to the attributes set by on all
135 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
136 the SMTP server refused.
137
138
139.. exception:: SMTPRecipientsRefused
140
141 All recipient addresses refused. The errors for each recipient are accessible
142 through the attribute :attr:`recipients`, which is a dictionary of exactly the
143 same sort as :meth:`SMTP.sendmail` returns.
144
145
146.. exception:: SMTPDataError
147
148 The SMTP server refused to accept the message data.
149
150
151.. exception:: SMTPConnectError
152
153 Error occurred during establishment of a connection with the server.
154
155
156.. exception:: SMTPHeloError
157
158 The server refused our ``HELO`` message.
159
160
161.. exception:: SMTPAuthenticationError
162
163 SMTP authentication went wrong. Most probably the server didn't accept the
164 username/password combination provided.
165
166
167.. seealso::
168
169 :rfc:`821` - Simple Mail Transfer Protocol
170 Protocol definition for SMTP. This document covers the model, operating
171 procedure, and protocol details for SMTP.
172
173 :rfc:`1869` - SMTP Service Extensions
174 Definition of the ESMTP extensions for SMTP. This describes a framework for
175 extending SMTP with new commands, supporting dynamic discovery of the commands
176 provided by the server, and defines a few additional commands.
177
178
179.. _smtp-objects:
180
181SMTP Objects
182------------
183
184An :class:`SMTP` instance has the following methods:
185
186
187.. method:: SMTP.set_debuglevel(level)
188
189 Set the debug output level. A true value for *level* results in debug messages
190 for connection and for all messages sent to and received from the server.
191
192
Georg Brandl18244152009-09-02 20:34:52 +0000193.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Georg Brandl18244152009-09-02 20:34:52 +0000195 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000196 concatenated to the command, separated by a space.
197
198 This returns a 2-tuple composed of a numeric response code and the actual
199 response line (multiline responses are joined into one long line.)
200
201 In normal operation it should not be necessary to call this method explicitly.
202 It is used to implement other methods and may be useful for testing private
203 extensions.
204
205 If the connection to the server is lost while waiting for the reply,
206 :exc:`SMTPServerDisconnected` will be raised.
207
208
R David Murray14ee3cf2013-04-13 14:40:33 -0400209.. method:: SMTP.connect(host='localhost', port=0)
210
211 Connect to a host on a given port. The defaults are to connect to the local
212 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
213 followed by a number, that suffix will be stripped off and the number
214 interpreted as the port number to use. This method is automatically invoked by
215 the constructor if a host is specified during instantiation. Returns a
216 2-tuple of the response code and message sent by the server in its
217 connection response.
218
219
Georg Brandl18244152009-09-02 20:34:52 +0000220.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222 Identify yourself to the SMTP server using ``HELO``. The hostname argument
223 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000224 The message returned by the server is stored as the :attr:`helo_resp` attribute
225 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227 In normal operation it should not be necessary to call this method explicitly.
228 It will be implicitly called by the :meth:`sendmail` when necessary.
229
230
Georg Brandl18244152009-09-02 20:34:52 +0000231.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
234 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000235 response for ESMTP option and store them for use by :meth:`has_extn`.
236 Also sets several informational attributes: the message returned by
237 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000238 is set to true or false depending on whether the server supports ESMTP, and
239 :attr:`esmtp_features` will be a dictionary containing the names of the
240 SMTP service extensions this server supports, and their
241 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
244 necessary to call this method explicitly. It will be implicitly called by
245 :meth:`sendmail` when necessary.
246
Christian Heimes679db4a2008-01-18 09:56:22 +0000247.. method:: SMTP.ehlo_or_helo_if_needed()
248
249 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
250 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
251 first.
252
Georg Brandl1f01deb2009-01-03 22:47:39 +0000253 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000254 The server didn't reply properly to the ``HELO`` greeting.
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256.. method:: SMTP.has_extn(name)
257
258 Return :const:`True` if *name* is in the set of SMTP service extensions returned
259 by the server, :const:`False` otherwise. Case is ignored.
260
261
262.. method:: SMTP.verify(address)
263
264 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
265 tuple consisting of code 250 and a full :rfc:`822` address (including human
266 name) if the user address is valid. Otherwise returns an SMTP error code of 400
267 or greater and an error string.
268
269 .. note::
270
271 Many sites disable SMTP ``VRFY`` in order to foil spammers.
272
273
274.. method:: SMTP.login(user, password)
275
276 Log in on an SMTP server that requires authentication. The arguments are the
277 username and the password to authenticate with. If there has been no previous
278 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
279 first. This method will return normally if the authentication was successful, or
280 may raise the following exceptions:
281
282 :exc:`SMTPHeloError`
283 The server didn't reply properly to the ``HELO`` greeting.
284
285 :exc:`SMTPAuthenticationError`
286 The server didn't accept the username/password combination.
287
288 :exc:`SMTPException`
289 No suitable authentication method was found.
290
291
Antoine Pitroue0650202011-05-18 18:03:09 +0200292.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
295 commands that follow will be encrypted. You should then call :meth:`ehlo`
296 again.
297
298 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
299 module's :func:`ssl` function.
300
Antoine Pitroue0650202011-05-18 18:03:09 +0200301 Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
302 using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
303
Christian Heimes679db4a2008-01-18 09:56:22 +0000304 If there has been no previous ``EHLO`` or ``HELO`` command this session,
305 this method tries ESMTP ``EHLO`` first.
306
Christian Heimes679db4a2008-01-18 09:56:22 +0000307 :exc:`SMTPHeloError`
308 The server didn't reply properly to the ``HELO`` greeting.
309
310 :exc:`SMTPException`
311 The server does not support the STARTTLS extension.
312
Christian Heimes679db4a2008-01-18 09:56:22 +0000313 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000314 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000315
Antoine Pitroue0650202011-05-18 18:03:09 +0200316 .. versionchanged:: 3.3
317 *context* was added.
318
Georg Brandl116aa622007-08-15 14:28:22 +0000319
Georg Brandl18244152009-09-02 20:34:52 +0000320.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322 Send mail. The required arguments are an :rfc:`822` from-address string, a list
323 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
324 address), and a message string. The caller may pass a list of ESMTP options
325 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
326 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
327 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
328 options to different recipients you have to use the low-level methods such as
329 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
330
331 .. note::
332
333 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000334 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000335 message headers in any way.
336
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600337 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000338 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600339 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
340 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000341
Georg Brandl116aa622007-08-15 14:28:22 +0000342 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
343 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
344 each of the specified options will be passed to it (if the option is in the
345 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
346 and ESMTP options suppressed.
347
348 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000349 recipient. Otherwise it will raise an exception. That is, if this method does
350 not raise an exception, then someone should get your mail. If this method does
351 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000352 recipient that was refused. Each entry contains a tuple of the SMTP error code
353 and the accompanying error message sent by the server.
354
355 This method may raise the following exceptions:
356
357 :exc:`SMTPRecipientsRefused`
358 All recipients were refused. Nobody got the mail. The :attr:`recipients`
359 attribute of the exception object is a dictionary with information about the
360 refused recipients (like the one returned when at least one recipient was
361 accepted).
362
363 :exc:`SMTPHeloError`
364 The server didn't reply properly to the ``HELO`` greeting.
365
366 :exc:`SMTPSenderRefused`
367 The server didn't accept the *from_addr*.
368
369 :exc:`SMTPDataError`
370 The server replied with an unexpected error code (other than a refusal of a
371 recipient).
372
373 Unless otherwise noted, the connection will be open even after an exception is
374 raised.
375
Georg Brandl61063cc2012-06-24 22:48:30 +0200376 .. versionchanged:: 3.2
377 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000378
379
R David Murrayac4e5ab2011-07-02 21:03:19 -0400380.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
381 mail_options=[], rcpt_options=[])
R. David Murray7dff9e02010-11-08 17:15:13 +0000382
383 This is a convenience method for calling :meth:`sendmail` with the message
384 represented by an :class:`email.message.Message` object. The arguments have
385 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
386 object.
387
R David Murrayac4e5ab2011-07-02 21:03:19 -0400388 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
389 those arguments with addresses extracted from the headers of *msg* as
390 specified in :rfc:`2822`\: *from_addr* is set to the :mailheader:`Sender`
391 field if it is present, and otherwise to the :mailheader:`From` field.
392 *to_adresses* combines the values (if any) of the :mailheader:`To`,
393 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
394 set of :mailheader:`Resent-*` headers appear in the message, the regular
395 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
396 If the message contains more than one set of :mailheader:`Resent-*` headers,
397 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
398 the most recent set of :mailheader:`Resent-` headers.
399
400 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000401 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400402 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
403 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
404 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
405 in *msg*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000406
407 .. versionadded:: 3.2
408
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410.. method:: SMTP.quit()
411
Christian Heimesba4af492008-03-28 00:55:15 +0000412 Terminate the SMTP session and close the connection. Return the result of
413 the SMTP ``QUIT`` command.
414
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
417``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
418Normally these do not need to be called directly, so they are not documented
419here. For details, consult the module code.
420
421
422.. _smtp-example:
423
424SMTP Example
425------------
426
427This example prompts the user for addresses needed in the message envelope ('To'
428and 'From' addresses), and the message to be delivered. Note that the headers
429to be included with the message must be included in the message as entered; this
430example doesn't do any processing of the :rfc:`822` headers. In particular, the
431'To' and 'From' addresses must be included in the message headers explicitly. ::
432
433 import smtplib
434
Georg Brandl116aa622007-08-15 14:28:22 +0000435 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000436 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438 fromaddr = prompt("From: ")
439 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000440 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442 # Add the From: and To: headers at the start!
443 msg = ("From: %s\r\nTo: %s\r\n\r\n"
444 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000445 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000446 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000447 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000448 except EOFError:
449 break
450 if not line:
451 break
452 msg = msg + line
453
Georg Brandl6911e3c2007-09-04 07:15:32 +0000454 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456 server = smtplib.SMTP('localhost')
457 server.set_debuglevel(1)
458 server.sendmail(fromaddr, toaddrs, msg)
459 server.quit()
460
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000461.. note::
462
463 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000464 construct an email message, which you can then send
465 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.