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