blob: 5762bb609f4b1d361f4f934abf1b4a5a69945c01 [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
R David Murray14ee3cf2013-04-13 14:40:33 -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 Murray0bfd6ac2013-04-13 14:40:51 -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). The optional source_address
33 parameter allows to bind to some specific source address in a machine with
34 multiple network interfaces, and/or to some specific source TCP port. It
35 takes a 2-tuple (host, port), for the socket to bind to as its source
36 address before connecting. If omitted (or if host or port are ``''`` and/or
37 0 respectively) the OS default behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39 For normal use, you should only require the initialization/connect,
Jesus Ceac73f8632012-12-26 16:47:03 +010040 :meth:`sendmail`, and :meth:`~smtplib.quit` methods.
41 An example is included below.
Georg Brandl116aa622007-08-15 14:28:22 +000042
Barry Warsaw1f5c9582011-03-15 15:04:44 -040043 The :class:`SMTP` class supports the :keyword:`with` statement. When used
44 like this, the SMTP ``QUIT`` command is issued automatically when the
45 :keyword:`with` statement exits. E.g.::
46
47 >>> from smtplib import SMTP
48 >>> with SMTP("domain.org") as smtp:
49 ... smtp.noop()
50 ...
51 (250, b'Ok')
52 >>>
53
Antoine Pitrou45456a02011-04-26 18:53:42 +020054 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040055 Support for the :keyword:`with` statement was added.
56
Senthil Kumaranb351a482011-07-31 09:14:17 +080057 .. versionchanged:: 3.3
58 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000059
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080060.. 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 +000061
62 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
63 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000064 required from the beginning of the connection and using :meth:`starttls` is
65 not appropriate. If *host* is not specified, the local host is used. If
Georg Brandl18244152009-09-02 20:34:52 +000066 *port* is zero, the standard SMTP-over-SSL port (465) is used. *keyfile*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000067 and *certfile* are also optional, and can contain a PEM formatted private key
Antoine Pitroue0650202011-05-18 18:03:09 +020068 and certificate chain file for the SSL connection. *context* also optional, can contain
69 a SSLContext, and is an alternative to keyfile and certfile; If it is specified both
70 keyfile and certfile must be None. The optional *timeout*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000071 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000072 connection attempt (if not specified, the global default timeout setting
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080073 will be used). The optional source_address parameter allows to bind to some
74 specific source address in a machine with multiple network interfaces,
75 and/or to some specific source tcp port. It takes a 2-tuple (host, port),
76 for the socket to bind to as its source address before connecting. If
Senthil Kumaranb351a482011-07-31 09:14:17 +080077 omitted (or if host or port are ``''`` and/or 0 respectively) the OS default
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080078 behavior will be used.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Antoine Pitroue0650202011-05-18 18:03:09 +020080 .. versionchanged:: 3.3
81 *context* was added.
82
Senthil Kumaranb351a482011-07-31 09:14:17 +080083 .. versionchanged:: 3.3
84 source_address argument was added.
Georg Brandl116aa622007-08-15 14:28:22 +000085
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080086
87.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000088
89 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080090 standard SMTP client. It's common to use Unix sockets for LMTP, so our
91 :meth:`connect` method must support that as well as a regular host:port
Senthil Kumaranb351a482011-07-31 09:14:17 +080092 server. The optional arguments local_hostname and source_address have the
93 same meaning as that of SMTP client. To specify a Unix socket, you must use
Senthil Kumaran63d4fb42011-07-30 10:58:30 +080094 an absolute path for *host*, starting with a '/'.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96 Authentication is supported, using the regular SMTP mechanism. When using a Unix
97 socket, LMTP generally don't support or require any authentication, but your
98 mileage might vary.
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101A nice selection of exceptions is defined as well:
102
103
104.. exception:: SMTPException
105
R David Murray8a345962013-04-14 06:46:35 -0400106 Subclass of :exc:`OSError` that is the base exception class for all
R David Murray8e37d5d2013-04-13 14:49:48 -0400107 the other excpetions provided by this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109
110.. exception:: SMTPServerDisconnected
111
112 This exception is raised when the server unexpectedly disconnects, or when an
113 attempt is made to use the :class:`SMTP` instance before connecting it to a
114 server.
115
116
117.. exception:: SMTPResponseException
118
119 Base class for all exceptions that include an SMTP error code. These exceptions
120 are generated in some instances when the SMTP server returns an error code. The
121 error code is stored in the :attr:`smtp_code` attribute of the error, and the
122 :attr:`smtp_error` attribute is set to the error message.
123
124
125.. exception:: SMTPSenderRefused
126
127 Sender address refused. In addition to the attributes set by on all
128 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
129 the SMTP server refused.
130
131
132.. exception:: SMTPRecipientsRefused
133
134 All recipient addresses refused. The errors for each recipient are accessible
135 through the attribute :attr:`recipients`, which is a dictionary of exactly the
136 same sort as :meth:`SMTP.sendmail` returns.
137
138
139.. exception:: SMTPDataError
140
141 The SMTP server refused to accept the message data.
142
143
144.. exception:: SMTPConnectError
145
146 Error occurred during establishment of a connection with the server.
147
148
149.. exception:: SMTPHeloError
150
151 The server refused our ``HELO`` message.
152
153
154.. exception:: SMTPAuthenticationError
155
156 SMTP authentication went wrong. Most probably the server didn't accept the
157 username/password combination provided.
158
159
160.. seealso::
161
162 :rfc:`821` - Simple Mail Transfer Protocol
163 Protocol definition for SMTP. This document covers the model, operating
164 procedure, and protocol details for SMTP.
165
166 :rfc:`1869` - SMTP Service Extensions
167 Definition of the ESMTP extensions for SMTP. This describes a framework for
168 extending SMTP with new commands, supporting dynamic discovery of the commands
169 provided by the server, and defines a few additional commands.
170
171
172.. _smtp-objects:
173
174SMTP Objects
175------------
176
177An :class:`SMTP` instance has the following methods:
178
179
180.. method:: SMTP.set_debuglevel(level)
181
182 Set the debug output level. A true value for *level* results in debug messages
183 for connection and for all messages sent to and received from the server.
184
185
Georg Brandl18244152009-09-02 20:34:52 +0000186.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl18244152009-09-02 20:34:52 +0000188 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000189 concatenated to the command, separated by a space.
190
191 This returns a 2-tuple composed of a numeric response code and the actual
192 response line (multiline responses are joined into one long line.)
193
194 In normal operation it should not be necessary to call this method explicitly.
195 It is used to implement other methods and may be useful for testing private
196 extensions.
197
198 If the connection to the server is lost while waiting for the reply,
199 :exc:`SMTPServerDisconnected` will be raised.
200
201
R David Murray14ee3cf2013-04-13 14:40:33 -0400202.. method:: SMTP.connect(host='localhost', port=0)
203
204 Connect to a host on a given port. The defaults are to connect to the local
205 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
206 followed by a number, that suffix will be stripped off and the number
207 interpreted as the port number to use. This method is automatically invoked by
208 the constructor if a host is specified during instantiation. Returns a
209 2-tuple of the response code and message sent by the server in its
210 connection response.
211
212
Georg Brandl18244152009-09-02 20:34:52 +0000213.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215 Identify yourself to the SMTP server using ``HELO``. The hostname argument
216 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000217 The message returned by the server is stored as the :attr:`helo_resp` attribute
218 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220 In normal operation it should not be necessary to call this method explicitly.
221 It will be implicitly called by the :meth:`sendmail` when necessary.
222
223
Georg Brandl18244152009-09-02 20:34:52 +0000224.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
227 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000228 response for ESMTP option and store them for use by :meth:`has_extn`.
229 Also sets several informational attributes: the message returned by
230 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000231 is set to true or false depending on whether the server supports ESMTP, and
232 :attr:`esmtp_features` will be a dictionary containing the names of the
233 SMTP service extensions this server supports, and their
234 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
237 necessary to call this method explicitly. It will be implicitly called by
238 :meth:`sendmail` when necessary.
239
Christian Heimes679db4a2008-01-18 09:56:22 +0000240.. method:: SMTP.ehlo_or_helo_if_needed()
241
242 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
243 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
244 first.
245
Georg Brandl1f01deb2009-01-03 22:47:39 +0000246 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000247 The server didn't reply properly to the ``HELO`` greeting.
248
Georg Brandl116aa622007-08-15 14:28:22 +0000249.. method:: SMTP.has_extn(name)
250
251 Return :const:`True` if *name* is in the set of SMTP service extensions returned
252 by the server, :const:`False` otherwise. Case is ignored.
253
254
255.. method:: SMTP.verify(address)
256
257 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
258 tuple consisting of code 250 and a full :rfc:`822` address (including human
259 name) if the user address is valid. Otherwise returns an SMTP error code of 400
260 or greater and an error string.
261
262 .. note::
263
264 Many sites disable SMTP ``VRFY`` in order to foil spammers.
265
266
267.. method:: SMTP.login(user, password)
268
269 Log in on an SMTP server that requires authentication. The arguments are the
270 username and the password to authenticate with. If there has been no previous
271 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
272 first. This method will return normally if the authentication was successful, or
273 may raise the following exceptions:
274
275 :exc:`SMTPHeloError`
276 The server didn't reply properly to the ``HELO`` greeting.
277
278 :exc:`SMTPAuthenticationError`
279 The server didn't accept the username/password combination.
280
281 :exc:`SMTPException`
282 No suitable authentication method was found.
283
284
Antoine Pitroue0650202011-05-18 18:03:09 +0200285.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
288 commands that follow will be encrypted. You should then call :meth:`ehlo`
289 again.
290
291 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
292 module's :func:`ssl` function.
293
Antoine Pitroue0650202011-05-18 18:03:09 +0200294 Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
295 using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
296
Christian Heimes679db4a2008-01-18 09:56:22 +0000297 If there has been no previous ``EHLO`` or ``HELO`` command this session,
298 this method tries ESMTP ``EHLO`` first.
299
Christian Heimes679db4a2008-01-18 09:56:22 +0000300 :exc:`SMTPHeloError`
301 The server didn't reply properly to the ``HELO`` greeting.
302
303 :exc:`SMTPException`
304 The server does not support the STARTTLS extension.
305
Christian Heimes679db4a2008-01-18 09:56:22 +0000306 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000307 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000308
Antoine Pitroue0650202011-05-18 18:03:09 +0200309 .. versionchanged:: 3.3
310 *context* was added.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Georg Brandl18244152009-09-02 20:34:52 +0000313.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315 Send mail. The required arguments are an :rfc:`822` from-address string, a list
316 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
317 address), and a message string. The caller may pass a list of ESMTP options
318 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
319 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
320 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
321 options to different recipients you have to use the low-level methods such as
322 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
323
324 .. note::
325
326 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000327 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000328 message headers in any way.
329
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600330 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000331 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600332 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
333 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000334
Georg Brandl116aa622007-08-15 14:28:22 +0000335 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
336 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
337 each of the specified options will be passed to it (if the option is in the
338 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
339 and ESMTP options suppressed.
340
341 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000342 recipient. Otherwise it will raise an exception. That is, if this method does
343 not raise an exception, then someone should get your mail. If this method does
344 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000345 recipient that was refused. Each entry contains a tuple of the SMTP error code
346 and the accompanying error message sent by the server.
347
348 This method may raise the following exceptions:
349
350 :exc:`SMTPRecipientsRefused`
351 All recipients were refused. Nobody got the mail. The :attr:`recipients`
352 attribute of the exception object is a dictionary with information about the
353 refused recipients (like the one returned when at least one recipient was
354 accepted).
355
356 :exc:`SMTPHeloError`
357 The server didn't reply properly to the ``HELO`` greeting.
358
359 :exc:`SMTPSenderRefused`
360 The server didn't accept the *from_addr*.
361
362 :exc:`SMTPDataError`
363 The server replied with an unexpected error code (other than a refusal of a
364 recipient).
365
366 Unless otherwise noted, the connection will be open even after an exception is
367 raised.
368
Georg Brandl61063cc2012-06-24 22:48:30 +0200369 .. versionchanged:: 3.2
370 *msg* may be a byte string.
R. David Murray7dff9e02010-11-08 17:15:13 +0000371
372
R David Murrayac4e5ab2011-07-02 21:03:19 -0400373.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
374 mail_options=[], rcpt_options=[])
R. David Murray7dff9e02010-11-08 17:15:13 +0000375
376 This is a convenience method for calling :meth:`sendmail` with the message
377 represented by an :class:`email.message.Message` object. The arguments have
378 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
379 object.
380
R David Murrayac4e5ab2011-07-02 21:03:19 -0400381 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
382 those arguments with addresses extracted from the headers of *msg* as
383 specified in :rfc:`2822`\: *from_addr* is set to the :mailheader:`Sender`
384 field if it is present, and otherwise to the :mailheader:`From` field.
385 *to_adresses* combines the values (if any) of the :mailheader:`To`,
386 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
387 set of :mailheader:`Resent-*` headers appear in the message, the regular
388 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
389 If the message contains more than one set of :mailheader:`Resent-*` headers,
390 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
391 the most recent set of :mailheader:`Resent-` headers.
392
393 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000394 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400395 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
396 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
397 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
398 in *msg*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000399
400 .. versionadded:: 3.2
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403.. method:: SMTP.quit()
404
Christian Heimesba4af492008-03-28 00:55:15 +0000405 Terminate the SMTP session and close the connection. Return the result of
406 the SMTP ``QUIT`` command.
407
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
410``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
411Normally these do not need to be called directly, so they are not documented
412here. For details, consult the module code.
413
414
415.. _smtp-example:
416
417SMTP Example
418------------
419
420This example prompts the user for addresses needed in the message envelope ('To'
421and 'From' addresses), and the message to be delivered. Note that the headers
422to be included with the message must be included in the message as entered; this
423example doesn't do any processing of the :rfc:`822` headers. In particular, the
424'To' and 'From' addresses must be included in the message headers explicitly. ::
425
426 import smtplib
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000429 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431 fromaddr = prompt("From: ")
432 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000433 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435 # Add the From: and To: headers at the start!
436 msg = ("From: %s\r\nTo: %s\r\n\r\n"
437 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000438 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000439 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000440 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000441 except EOFError:
442 break
443 if not line:
444 break
445 msg = msg + line
446
Georg Brandl6911e3c2007-09-04 07:15:32 +0000447 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449 server = smtplib.SMTP('localhost')
450 server.set_debuglevel(1)
451 server.sendmail(fromaddr, toaddrs, msg)
452 server.quit()
453
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000454.. note::
455
456 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000457 construct an email message, which you can then send
458 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.