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