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