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