blob: cad4b41389b5da70bd2a6ead4432c92441cc3fa7 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Éric Araujo29a0b572011-08-19 02:14:03 +020013**Source code:** :source:`Lib/smtplib.py`
14
15--------------
16
Georg Brandl8ec7f652007-08-15 14:28:01 +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
23.. class:: SMTP([host[, port[, local_hostname[, timeout]]]])
24
Georg Brandlab756f62008-05-11 11:09:35 +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
27 host and port parameters are given, the SMTP :meth:`connect` method is called
R David Murray2fc97e62013-04-13 14:37:22 -040028 with those parameters during initialization. If the :meth:`connect` call
29 returns anything other than a success code, an :exc:`SMTPConnectError` is
30 raised. The optional
Georg Brandlab756f62008-05-11 11:09:35 +000031 *timeout* parameter specifies a timeout in seconds for blocking operations
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000032 like the connection attempt (if not specified, the global default timeout
33 setting will be used).
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35 For normal use, you should only require the initialization/connect,
Jesus Cea49470492012-12-26 16:46:04 +010036 :meth:`sendmail`, and :meth:`~smtplib.quit` methods.
37 An example is included below.
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39 .. versionchanged:: 2.6
40 *timeout* was added.
41
42
43.. class:: SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])
44
45 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
46 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Georg Brandlab756f62008-05-11 11:09:35 +000047 required from the beginning of the connection and using :meth:`starttls` is
48 not appropriate. If *host* is not specified, the local host is used. If
49 *port* is omitted, the standard SMTP-over-SSL port (465) is used. *keyfile*
50 and *certfile* are also optional, and can contain a PEM formatted private key
51 and certificate chain file for the SSL connection. The optional *timeout*
52 parameter specifies a timeout in seconds for blocking operations like the
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000053 connection attempt (if not specified, the global default timeout setting
54 will be used).
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
Georg Brandl6e102942010-11-05 07:37:51 +000056 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +000057
58
59.. class:: LMTP([host[, port[, local_hostname]]])
60
61 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Andrew M. Kuchling24e99c42007-09-01 20:31:59 +000062 standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect`
Georg Brandl8ec7f652007-08-15 14:28:01 +000063 method must support that as well as a regular host:port server. To specify a
64 Unix socket, you must use an absolute path for *host*, starting with a '/'.
65
66 Authentication is supported, using the regular SMTP mechanism. When using a Unix
67 socket, LMTP generally don't support or require any authentication, but your
68 mileage might vary.
69
70 .. versionadded:: 2.6
71
72A nice selection of exceptions is defined as well:
73
74
75.. exception:: SMTPException
76
R David Murray2fc97e62013-04-13 14:37:22 -040077 The base exception class for all the other excpetions provided by this
78 module.
Georg Brandl8ec7f652007-08-15 14:28:01 +000079
80
81.. exception:: SMTPServerDisconnected
82
83 This exception is raised when the server unexpectedly disconnects, or when an
84 attempt is made to use the :class:`SMTP` instance before connecting it to a
85 server.
86
87
88.. exception:: SMTPResponseException
89
90 Base class for all exceptions that include an SMTP error code. These exceptions
91 are generated in some instances when the SMTP server returns an error code. The
92 error code is stored in the :attr:`smtp_code` attribute of the error, and the
93 :attr:`smtp_error` attribute is set to the error message.
94
95
96.. exception:: SMTPSenderRefused
97
98 Sender address refused. In addition to the attributes set by on all
99 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
100 the SMTP server refused.
101
102
103.. exception:: SMTPRecipientsRefused
104
105 All recipient addresses refused. The errors for each recipient are accessible
106 through the attribute :attr:`recipients`, which is a dictionary of exactly the
107 same sort as :meth:`SMTP.sendmail` returns.
108
109
110.. exception:: SMTPDataError
111
112 The SMTP server refused to accept the message data.
113
114
115.. exception:: SMTPConnectError
116
117 Error occurred during establishment of a connection with the server.
118
119
120.. exception:: SMTPHeloError
121
122 The server refused our ``HELO`` message.
123
124
125.. exception:: SMTPAuthenticationError
126
127 SMTP authentication went wrong. Most probably the server didn't accept the
128 username/password combination provided.
129
130
131.. seealso::
132
133 :rfc:`821` - Simple Mail Transfer Protocol
134 Protocol definition for SMTP. This document covers the model, operating
135 procedure, and protocol details for SMTP.
136
137 :rfc:`1869` - SMTP Service Extensions
138 Definition of the ESMTP extensions for SMTP. This describes a framework for
139 extending SMTP with new commands, supporting dynamic discovery of the commands
140 provided by the server, and defines a few additional commands.
141
142
143.. _smtp-objects:
144
145SMTP Objects
146------------
147
148An :class:`SMTP` instance has the following methods:
149
150
151.. method:: SMTP.set_debuglevel(level)
152
153 Set the debug output level. A true value for *level* results in debug messages
154 for connection and for all messages sent to and received from the server.
155
156
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157.. method:: SMTP.docmd(cmd, [, argstring])
158
159 Send a command *cmd* to the server. The optional argument *argstring* is simply
160 concatenated to the command, separated by a space.
161
162 This returns a 2-tuple composed of a numeric response code and the actual
163 response line (multiline responses are joined into one long line.)
164
165 In normal operation it should not be necessary to call this method explicitly.
166 It is used to implement other methods and may be useful for testing private
167 extensions.
168
169 If the connection to the server is lost while waiting for the reply,
170 :exc:`SMTPServerDisconnected` will be raised.
171
172
R David Murray2fc97e62013-04-13 14:37:22 -0400173.. method:: SMTP.connect([host[, port]])
174
175 Connect to a host on a given port. The defaults are to connect to the local
176 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
177 followed by a number, that suffix will be stripped off and the number
178 interpreted as the port number to use. This method is automatically invoked by
179 the constructor if a host is specified during instantiation. Returns a
180 2-tuple of the response code and message sent by the server in its
181 connection response.
182
183
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184.. method:: SMTP.helo([hostname])
185
186 Identify yourself to the SMTP server using ``HELO``. The hostname argument
187 defaults to the fully qualified domain name of the local host.
Andrew M. Kuchlingfe38e442008-09-06 21:26:02 +0000188 The message returned by the server is stored as the :attr:`helo_resp` attribute
189 of the object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000190
191 In normal operation it should not be necessary to call this method explicitly.
192 It will be implicitly called by the :meth:`sendmail` when necessary.
193
194
195.. method:: SMTP.ehlo([hostname])
196
197 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
198 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000199 response for ESMTP option and store them for use by :meth:`has_extn`.
200 Also sets several informational attributes: the message returned by
201 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Andrew M. Kuchlingfe38e442008-09-06 21:26:02 +0000202 is set to true or false depending on whether the server supports ESMTP, and
203 :attr:`esmtp_features` will be a dictionary containing the names of the
204 SMTP service extensions this server supports, and their
205 parameters (if any).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206
207 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
208 necessary to call this method explicitly. It will be implicitly called by
209 :meth:`sendmail` when necessary.
210
Gregory P. Smithbde4ae42008-01-17 08:35:49 +0000211.. method:: SMTP.ehlo_or_helo_if_needed()
212
213 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
214 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
215 first.
216
Georg Brandlfc29f272009-01-02 20:25:14 +0000217 :exc:`SMTPHeloError`
Gregory P. Smithbde4ae42008-01-17 08:35:49 +0000218 The server didn't reply properly to the ``HELO`` greeting.
219
220 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221
222.. method:: SMTP.has_extn(name)
223
224 Return :const:`True` if *name* is in the set of SMTP service extensions returned
225 by the server, :const:`False` otherwise. Case is ignored.
226
227
228.. method:: SMTP.verify(address)
229
230 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
231 tuple consisting of code 250 and a full :rfc:`822` address (including human
232 name) if the user address is valid. Otherwise returns an SMTP error code of 400
233 or greater and an error string.
234
235 .. note::
236
237 Many sites disable SMTP ``VRFY`` in order to foil spammers.
238
239
240.. method:: SMTP.login(user, password)
241
242 Log in on an SMTP server that requires authentication. The arguments are the
243 username and the password to authenticate with. If there has been no previous
244 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
245 first. This method will return normally if the authentication was successful, or
246 may raise the following exceptions:
247
248 :exc:`SMTPHeloError`
249 The server didn't reply properly to the ``HELO`` greeting.
250
251 :exc:`SMTPAuthenticationError`
252 The server didn't accept the username/password combination.
253
254 :exc:`SMTPException`
255 No suitable authentication method was found.
256
257
258.. method:: SMTP.starttls([keyfile[, certfile]])
259
260 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
261 commands that follow will be encrypted. You should then call :meth:`ehlo`
262 again.
263
264 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
265 module's :func:`ssl` function.
266
Gregory P. Smithbde4ae42008-01-17 08:35:49 +0000267 If there has been no previous ``EHLO`` or ``HELO`` command this session,
268 this method tries ESMTP ``EHLO`` first.
269
270 .. versionchanged:: 2.6
271
272 :exc:`SMTPHeloError`
273 The server didn't reply properly to the ``HELO`` greeting.
274
275 :exc:`SMTPException`
276 The server does not support the STARTTLS extension.
277
278 .. versionchanged:: 2.6
279
280 :exc:`RuntimeError`
Ezio Melotti062d2b52009-12-19 22:41:49 +0000281 SSL/TLS support is not available to your Python interpreter.
Gregory P. Smithbde4ae42008-01-17 08:35:49 +0000282
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
284.. method:: SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
285
286 Send mail. The required arguments are an :rfc:`822` from-address string, a list
287 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
288 address), and a message string. The caller may pass a list of ESMTP options
289 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
290 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
291 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
292 options to different recipients you have to use the low-level methods such as
293 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
294
295 .. note::
296
297 The *from_addr* and *to_addrs* parameters are used to construct the message
298 envelope used by the transport agents. The :class:`SMTP` does not modify the
299 message headers in any way.
300
301 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
302 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
303 each of the specified options will be passed to it (if the option is in the
304 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
305 and ESMTP options suppressed.
306
307 This method will return normally if the mail is accepted for at least one
Georg Brandl21946af2010-10-06 09:28:45 +0000308 recipient. Otherwise it will raise an exception. That is, if this method does
309 not raise an exception, then someone should get your mail. If this method does
310 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311 recipient that was refused. Each entry contains a tuple of the SMTP error code
312 and the accompanying error message sent by the server.
313
314 This method may raise the following exceptions:
315
316 :exc:`SMTPRecipientsRefused`
317 All recipients were refused. Nobody got the mail. The :attr:`recipients`
318 attribute of the exception object is a dictionary with information about the
319 refused recipients (like the one returned when at least one recipient was
320 accepted).
321
322 :exc:`SMTPHeloError`
323 The server didn't reply properly to the ``HELO`` greeting.
324
325 :exc:`SMTPSenderRefused`
326 The server didn't accept the *from_addr*.
327
328 :exc:`SMTPDataError`
329 The server replied with an unexpected error code (other than a refusal of a
330 recipient).
331
332 Unless otherwise noted, the connection will be open even after an exception is
333 raised.
334
335
336.. method:: SMTP.quit()
337
Georg Brandldeaf2ca2008-03-27 13:27:31 +0000338 Terminate the SMTP session and close the connection. Return the result of
339 the SMTP ``QUIT`` command.
340
341 .. versionchanged:: 2.6
342 Return a value.
343
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344
345Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
346``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
347Normally these do not need to be called directly, so they are not documented
348here. For details, consult the module code.
349
350
351.. _smtp-example:
352
353SMTP Example
354------------
355
356This example prompts the user for addresses needed in the message envelope ('To'
357and 'From' addresses), and the message to be delivered. Note that the headers
358to be included with the message must be included in the message as entered; this
359example doesn't do any processing of the :rfc:`822` headers. In particular, the
360'To' and 'From' addresses must be included in the message headers explicitly. ::
361
362 import smtplib
363
364 def prompt(prompt):
365 return raw_input(prompt).strip()
366
367 fromaddr = prompt("From: ")
368 toaddrs = prompt("To: ").split()
369 print "Enter message, end with ^D (Unix) or ^Z (Windows):"
370
371 # Add the From: and To: headers at the start!
372 msg = ("From: %s\r\nTo: %s\r\n\r\n"
373 % (fromaddr, ", ".join(toaddrs)))
374 while 1:
375 try:
376 line = raw_input()
377 except EOFError:
378 break
379 if not line:
380 break
381 msg = msg + line
382
383 print "Message length is " + repr(len(msg))
384
385 server = smtplib.SMTP('localhost')
386 server.set_debuglevel(1)
387 server.sendmail(fromaddr, toaddrs, msg)
388 server.quit()
389
Georg Brandlac2380b2009-05-20 18:35:27 +0000390.. note::
391
392 In general, you will want to use the :mod:`email` package's features to
393 construct an email message, which you can then convert to a string and send
394 via :meth:`sendmail`; see :ref:`email-examples`.