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