blob: 4a0f75677a5927e9ffd74c411cfcf88e1f84706a [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Raymond Hettinger469271d2011-01-27 20:38:46 +000013**Source code:** :source:`Lib/smtplib.py`
14
15--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +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
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080023.. class:: SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000024
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +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
Georg Brandlf78e02b2008-06-10 17:40:04 +000031 like the connection attempt (if not specified, the global default timeout
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080032 setting will be used). The optional source_address parameter allows to bind to some
33 specific source address in a machine with multiple network interfaces,
34 and/or to some specific source tcp port. It takes a 2-tuple (host, port),
35 for the socket to bind to as its source address before connecting. If
36 ommited (or if host or port are '' and/or 0 respectively) the OS default
37 behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39 For normal use, you should only require the initialization/connect,
40 :meth:`sendmail`, and :meth:`quit` methods. An example is included below.
41
Barry Warsaw1f5c9582011-03-15 15:04:44 -040042 The :class:`SMTP` class supports the :keyword:`with` statement. When used
43 like this, the SMTP ``QUIT`` command is issued automatically when the
44 :keyword:`with` statement exits. E.g.::
45
46 >>> from smtplib import SMTP
47 >>> with SMTP("domain.org") as smtp:
48 ... smtp.noop()
49 ...
50 (250, b'Ok')
51 >>>
52
Antoine Pitrou45456a02011-04-26 18:53:42 +020053 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040054 Support for the :keyword:`with` statement was added.
55
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080056 .. versionadded:: 3.3
57 source_address parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000058
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080059.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout], context=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000060
61 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
62 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000063 required from the beginning of the connection and using :meth:`starttls` is
64 not appropriate. If *host* is not specified, the local host is used. If
Georg Brandl18244152009-09-02 20:34:52 +000065 *port* is zero, the standard SMTP-over-SSL port (465) is used. *keyfile*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000066 and *certfile* are also optional, and can contain a PEM formatted private key
Antoine Pitroue0650202011-05-18 18:03:09 +020067 and certificate chain file for the SSL connection. *context* also optional, can contain
68 a SSLContext, and is an alternative to keyfile and certfile; If it is specified both
69 keyfile and certfile must be None. The optional *timeout*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000070 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000071 connection attempt (if not specified, the global default timeout setting
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080072 will be used). The optional source_address parameter allows to bind to some
73 specific source address in a machine with multiple network interfaces,
74 and/or to some specific source tcp port. It takes a 2-tuple (host, port),
75 for the socket to bind to as its source address before connecting. If
76 ommited (or if host or port are '' and/or 0 respectively) the OS default
77 behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000078
Antoine Pitroue0650202011-05-18 18:03:09 +020079 .. versionchanged:: 3.3
80 *context* was added.
81
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080082 .. versionadded:: 3.3
83 source_address parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000084
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080085
86.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080089 standard SMTP client. It's common to use Unix sockets for LMTP, so our
90 :meth:`connect` method must support that as well as a regular host:port
91 server. The optional parameters local_hostname and source_address has the
92 same meaning as that of SMTP client.To specify a Unix socket, you must use
Senthil Kumaran63d4fb42011-07-30 10:58:30 +080093 an absolute path for *host*, starting with a '/'.
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 Authentication is supported, using the regular SMTP mechanism. When using a Unix
96 socket, LMTP generally don't support or require any authentication, but your
97 mileage might vary.
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
100A nice selection of exceptions is defined as well:
101
102
103.. exception:: SMTPException
104
105 Base exception class for all exceptions raised by this module.
106
107
108.. exception:: SMTPServerDisconnected
109
110 This exception is raised when the server unexpectedly disconnects, or when an
111 attempt is made to use the :class:`SMTP` instance before connecting it to a
112 server.
113
114
115.. exception:: SMTPResponseException
116
117 Base class for all exceptions that include an SMTP error code. These exceptions
118 are generated in some instances when the SMTP server returns an error code. The
119 error code is stored in the :attr:`smtp_code` attribute of the error, and the
120 :attr:`smtp_error` attribute is set to the error message.
121
122
123.. exception:: SMTPSenderRefused
124
125 Sender address refused. In addition to the attributes set by on all
126 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
127 the SMTP server refused.
128
129
130.. exception:: SMTPRecipientsRefused
131
132 All recipient addresses refused. The errors for each recipient are accessible
133 through the attribute :attr:`recipients`, which is a dictionary of exactly the
134 same sort as :meth:`SMTP.sendmail` returns.
135
136
137.. exception:: SMTPDataError
138
139 The SMTP server refused to accept the message data.
140
141
142.. exception:: SMTPConnectError
143
144 Error occurred during establishment of a connection with the server.
145
146
147.. exception:: SMTPHeloError
148
149 The server refused our ``HELO`` message.
150
151
152.. exception:: SMTPAuthenticationError
153
154 SMTP authentication went wrong. Most probably the server didn't accept the
155 username/password combination provided.
156
157
158.. seealso::
159
160 :rfc:`821` - Simple Mail Transfer Protocol
161 Protocol definition for SMTP. This document covers the model, operating
162 procedure, and protocol details for SMTP.
163
164 :rfc:`1869` - SMTP Service Extensions
165 Definition of the ESMTP extensions for SMTP. This describes a framework for
166 extending SMTP with new commands, supporting dynamic discovery of the commands
167 provided by the server, and defines a few additional commands.
168
169
170.. _smtp-objects:
171
172SMTP Objects
173------------
174
175An :class:`SMTP` instance has the following methods:
176
177
178.. method:: SMTP.set_debuglevel(level)
179
180 Set the debug output level. A true value for *level* results in debug messages
181 for connection and for all messages sent to and received from the server.
182
183
Georg Brandl18244152009-09-02 20:34:52 +0000184.. method:: SMTP.connect(host='localhost', port=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186 Connect to a host on a given port. The defaults are to connect to the local
187 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
188 followed by a number, that suffix will be stripped off and the number
189 interpreted as the port number to use. This method is automatically invoked by
190 the constructor if a host is specified during instantiation.
191
192
Georg Brandl18244152009-09-02 20:34:52 +0000193.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Georg Brandl18244152009-09-02 20:34:52 +0000195 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000196 concatenated to the command, separated by a space.
197
198 This returns a 2-tuple composed of a numeric response code and the actual
199 response line (multiline responses are joined into one long line.)
200
201 In normal operation it should not be necessary to call this method explicitly.
202 It is used to implement other methods and may be useful for testing private
203 extensions.
204
205 If the connection to the server is lost while waiting for the reply,
206 :exc:`SMTPServerDisconnected` will be raised.
207
208
Georg Brandl18244152009-09-02 20:34:52 +0000209.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211 Identify yourself to the SMTP server using ``HELO``. The hostname argument
212 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000213 The message returned by the server is stored as the :attr:`helo_resp` attribute
214 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216 In normal operation it should not be necessary to call this method explicitly.
217 It will be implicitly called by the :meth:`sendmail` when necessary.
218
219
Georg Brandl18244152009-09-02 20:34:52 +0000220.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
223 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000224 response for ESMTP option and store them for use by :meth:`has_extn`.
225 Also sets several informational attributes: the message returned by
226 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000227 is set to true or false depending on whether the server supports ESMTP, and
228 :attr:`esmtp_features` will be a dictionary containing the names of the
229 SMTP service extensions this server supports, and their
230 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000231
232 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
233 necessary to call this method explicitly. It will be implicitly called by
234 :meth:`sendmail` when necessary.
235
Christian Heimes679db4a2008-01-18 09:56:22 +0000236.. method:: SMTP.ehlo_or_helo_if_needed()
237
238 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
239 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
240 first.
241
Georg Brandl1f01deb2009-01-03 22:47:39 +0000242 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000243 The server didn't reply properly to the ``HELO`` greeting.
244
Georg Brandl116aa622007-08-15 14:28:22 +0000245.. method:: SMTP.has_extn(name)
246
247 Return :const:`True` if *name* is in the set of SMTP service extensions returned
248 by the server, :const:`False` otherwise. Case is ignored.
249
250
251.. method:: SMTP.verify(address)
252
253 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
254 tuple consisting of code 250 and a full :rfc:`822` address (including human
255 name) if the user address is valid. Otherwise returns an SMTP error code of 400
256 or greater and an error string.
257
258 .. note::
259
260 Many sites disable SMTP ``VRFY`` in order to foil spammers.
261
262
263.. method:: SMTP.login(user, password)
264
265 Log in on an SMTP server that requires authentication. The arguments are the
266 username and the password to authenticate with. If there has been no previous
267 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
268 first. This method will return normally if the authentication was successful, or
269 may raise the following exceptions:
270
271 :exc:`SMTPHeloError`
272 The server didn't reply properly to the ``HELO`` greeting.
273
274 :exc:`SMTPAuthenticationError`
275 The server didn't accept the username/password combination.
276
277 :exc:`SMTPException`
278 No suitable authentication method was found.
279
280
Antoine Pitroue0650202011-05-18 18:03:09 +0200281.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
284 commands that follow will be encrypted. You should then call :meth:`ehlo`
285 again.
286
287 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
288 module's :func:`ssl` function.
289
Antoine Pitroue0650202011-05-18 18:03:09 +0200290 Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
291 using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
292
Christian Heimes679db4a2008-01-18 09:56:22 +0000293 If there has been no previous ``EHLO`` or ``HELO`` command this session,
294 this method tries ESMTP ``EHLO`` first.
295
Christian Heimes679db4a2008-01-18 09:56:22 +0000296 :exc:`SMTPHeloError`
297 The server didn't reply properly to the ``HELO`` greeting.
298
299 :exc:`SMTPException`
300 The server does not support the STARTTLS extension.
301
Christian Heimes679db4a2008-01-18 09:56:22 +0000302 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000303 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000304
Antoine Pitroue0650202011-05-18 18:03:09 +0200305 .. versionchanged:: 3.3
306 *context* was added.
307
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Georg Brandl18244152009-09-02 20:34:52 +0000309.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311 Send mail. The required arguments are an :rfc:`822` from-address string, a list
312 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
313 address), and a message string. The caller may pass a list of ESMTP options
314 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
315 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
316 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
317 options to different recipients you have to use the low-level methods such as
318 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
319
320 .. note::
321
322 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000323 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000324 message headers in any way.
325
R. David Murray7dff9e02010-11-08 17:15:13 +0000326 msg may be a string containing characters in the ASCII range, or a byte
327 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
328 and ``\n`` characters are converted to ``\r\n`` characters. A byte string
329 is not modified.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
332 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
333 each of the specified options will be passed to it (if the option is in the
334 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
335 and ESMTP options suppressed.
336
337 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000338 recipient. Otherwise it will raise an exception. That is, if this method does
339 not raise an exception, then someone should get your mail. If this method does
340 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000341 recipient that was refused. Each entry contains a tuple of the SMTP error code
342 and the accompanying error message sent by the server.
343
344 This method may raise the following exceptions:
345
346 :exc:`SMTPRecipientsRefused`
347 All recipients were refused. Nobody got the mail. The :attr:`recipients`
348 attribute of the exception object is a dictionary with information about the
349 refused recipients (like the one returned when at least one recipient was
350 accepted).
351
352 :exc:`SMTPHeloError`
353 The server didn't reply properly to the ``HELO`` greeting.
354
355 :exc:`SMTPSenderRefused`
356 The server didn't accept the *from_addr*.
357
358 :exc:`SMTPDataError`
359 The server replied with an unexpected error code (other than a refusal of a
360 recipient).
361
362 Unless otherwise noted, the connection will be open even after an exception is
363 raised.
364
R. David Murray7dff9e02010-11-08 17:15:13 +0000365 .. versionchanged:: 3.2 *msg* may be a byte string.
366
367
R David Murrayac4e5ab2011-07-02 21:03:19 -0400368.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
369 mail_options=[], rcpt_options=[])
R. David Murray7dff9e02010-11-08 17:15:13 +0000370
371 This is a convenience method for calling :meth:`sendmail` with the message
372 represented by an :class:`email.message.Message` object. The arguments have
373 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
374 object.
375
R David Murrayac4e5ab2011-07-02 21:03:19 -0400376 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
377 those arguments with addresses extracted from the headers of *msg* as
378 specified in :rfc:`2822`\: *from_addr* is set to the :mailheader:`Sender`
379 field if it is present, and otherwise to the :mailheader:`From` field.
380 *to_adresses* combines the values (if any) of the :mailheader:`To`,
381 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
382 set of :mailheader:`Resent-*` headers appear in the message, the regular
383 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
384 If the message contains more than one set of :mailheader:`Resent-*` headers,
385 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
386 the most recent set of :mailheader:`Resent-` headers.
387
388 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000389 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400390 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
391 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
392 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
393 in *msg*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000394
395 .. versionadded:: 3.2
396
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398.. method:: SMTP.quit()
399
Christian Heimesba4af492008-03-28 00:55:15 +0000400 Terminate the SMTP session and close the connection. Return the result of
401 the SMTP ``QUIT`` command.
402
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
405``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
406Normally these do not need to be called directly, so they are not documented
407here. For details, consult the module code.
408
409
410.. _smtp-example:
411
412SMTP Example
413------------
414
415This example prompts the user for addresses needed in the message envelope ('To'
416and 'From' addresses), and the message to be delivered. Note that the headers
417to be included with the message must be included in the message as entered; this
418example doesn't do any processing of the :rfc:`822` headers. In particular, the
419'To' and 'From' addresses must be included in the message headers explicitly. ::
420
421 import smtplib
422
Georg Brandl116aa622007-08-15 14:28:22 +0000423 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000424 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426 fromaddr = prompt("From: ")
427 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000428 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430 # Add the From: and To: headers at the start!
431 msg = ("From: %s\r\nTo: %s\r\n\r\n"
432 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000433 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000434 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000435 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000436 except EOFError:
437 break
438 if not line:
439 break
440 msg = msg + line
441
Georg Brandl6911e3c2007-09-04 07:15:32 +0000442 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444 server = smtplib.SMTP('localhost')
445 server.set_debuglevel(1)
446 server.sendmail(fromaddr, toaddrs, msg)
447 server.quit()
448
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000449.. note::
450
451 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000452 construct an email message, which you can then send
453 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.