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