blob: b432d3ec16803bf2816c8954afd96b0d210fad21 [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
Georg Brandl18244152009-09-02 20:34:52 +000023.. class:: SMTP(host='', port=0, local_hostname=None[, timeout])
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
32 setting will be used).
Georg Brandl116aa622007-08-15 14:28:22 +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
Barry Warsaw1f5c9582011-03-15 15:04:44 -040037 The :class:`SMTP` class supports the :keyword:`with` statement. When used
38 like this, the SMTP ``QUIT`` command is issued automatically when the
39 :keyword:`with` statement exits. E.g.::
40
41 >>> from smtplib import SMTP
42 >>> with SMTP("domain.org") as smtp:
43 ... smtp.noop()
44 ...
45 (250, b'Ok')
46 >>>
47
Antoine Pitrou45456a02011-04-26 18:53:42 +020048 .. versionchanged:: 3.3
Barry Warsaw1f5c9582011-03-15 15:04:44 -040049 Support for the :keyword:`with` statement was added.
50
Georg Brandl116aa622007-08-15 14:28:22 +000051
Antoine Pitroue0650202011-05-18 18:03:09 +020052.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout], context=None)
Georg Brandl116aa622007-08-15 14:28:22 +000053
54 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
55 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000056 required from the beginning of the connection and using :meth:`starttls` is
57 not appropriate. If *host* is not specified, the local host is used. If
Georg Brandl18244152009-09-02 20:34:52 +000058 *port* is zero, the standard SMTP-over-SSL port (465) is used. *keyfile*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000059 and *certfile* are also optional, and can contain a PEM formatted private key
Antoine Pitroue0650202011-05-18 18:03:09 +020060 and certificate chain file for the SSL connection. *context* also optional, can contain
61 a SSLContext, and is an alternative to keyfile and certfile; If it is specified both
62 keyfile and certfile must be None. The optional *timeout*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000063 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000064 connection attempt (if not specified, the global default timeout setting
65 will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000066
Antoine Pitroue0650202011-05-18 18:03:09 +020067 .. versionchanged:: 3.3
68 *context* was added.
69
Georg Brandl116aa622007-08-15 14:28:22 +000070
Georg Brandl18244152009-09-02 20:34:52 +000071.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000074 standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +000075 method must support that as well as a regular host:port server. To specify a
76 Unix socket, you must use an absolute path for *host*, starting with a '/'.
77
78 Authentication is supported, using the regular SMTP mechanism. When using a Unix
79 socket, LMTP generally don't support or require any authentication, but your
80 mileage might vary.
81
Georg Brandl116aa622007-08-15 14:28:22 +000082
83A nice selection of exceptions is defined as well:
84
85
86.. exception:: SMTPException
87
88 Base exception class for all exceptions raised by this module.
89
90
91.. exception:: SMTPServerDisconnected
92
93 This exception is raised when the server unexpectedly disconnects, or when an
94 attempt is made to use the :class:`SMTP` instance before connecting it to a
95 server.
96
97
98.. exception:: SMTPResponseException
99
100 Base class for all exceptions that include an SMTP error code. These exceptions
101 are generated in some instances when the SMTP server returns an error code. The
102 error code is stored in the :attr:`smtp_code` attribute of the error, and the
103 :attr:`smtp_error` attribute is set to the error message.
104
105
106.. exception:: SMTPSenderRefused
107
108 Sender address refused. In addition to the attributes set by on all
109 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
110 the SMTP server refused.
111
112
113.. exception:: SMTPRecipientsRefused
114
115 All recipient addresses refused. The errors for each recipient are accessible
116 through the attribute :attr:`recipients`, which is a dictionary of exactly the
117 same sort as :meth:`SMTP.sendmail` returns.
118
119
120.. exception:: SMTPDataError
121
122 The SMTP server refused to accept the message data.
123
124
125.. exception:: SMTPConnectError
126
127 Error occurred during establishment of a connection with the server.
128
129
130.. exception:: SMTPHeloError
131
132 The server refused our ``HELO`` message.
133
134
135.. exception:: SMTPAuthenticationError
136
137 SMTP authentication went wrong. Most probably the server didn't accept the
138 username/password combination provided.
139
140
141.. seealso::
142
143 :rfc:`821` - Simple Mail Transfer Protocol
144 Protocol definition for SMTP. This document covers the model, operating
145 procedure, and protocol details for SMTP.
146
147 :rfc:`1869` - SMTP Service Extensions
148 Definition of the ESMTP extensions for SMTP. This describes a framework for
149 extending SMTP with new commands, supporting dynamic discovery of the commands
150 provided by the server, and defines a few additional commands.
151
152
153.. _smtp-objects:
154
155SMTP Objects
156------------
157
158An :class:`SMTP` instance has the following methods:
159
160
161.. method:: SMTP.set_debuglevel(level)
162
163 Set the debug output level. A true value for *level* results in debug messages
164 for connection and for all messages sent to and received from the server.
165
166
Georg Brandl18244152009-09-02 20:34:52 +0000167.. method:: SMTP.connect(host='localhost', port=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169 Connect to a host on a given port. The defaults are to connect to the local
170 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
171 followed by a number, that suffix will be stripped off and the number
172 interpreted as the port number to use. This method is automatically invoked by
173 the constructor if a host is specified during instantiation.
174
175
Georg Brandl18244152009-09-02 20:34:52 +0000176.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Georg Brandl18244152009-09-02 20:34:52 +0000178 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000179 concatenated to the command, separated by a space.
180
181 This returns a 2-tuple composed of a numeric response code and the actual
182 response line (multiline responses are joined into one long line.)
183
184 In normal operation it should not be necessary to call this method explicitly.
185 It is used to implement other methods and may be useful for testing private
186 extensions.
187
188 If the connection to the server is lost while waiting for the reply,
189 :exc:`SMTPServerDisconnected` will be raised.
190
191
Georg Brandl18244152009-09-02 20:34:52 +0000192.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194 Identify yourself to the SMTP server using ``HELO``. The hostname argument
195 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000196 The message returned by the server is stored as the :attr:`helo_resp` attribute
197 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199 In normal operation it should not be necessary to call this method explicitly.
200 It will be implicitly called by the :meth:`sendmail` when necessary.
201
202
Georg Brandl18244152009-09-02 20:34:52 +0000203.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
206 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000207 response for ESMTP option and store them for use by :meth:`has_extn`.
208 Also sets several informational attributes: the message returned by
209 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000210 is set to true or false depending on whether the server supports ESMTP, and
211 :attr:`esmtp_features` will be a dictionary containing the names of the
212 SMTP service extensions this server supports, and their
213 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
216 necessary to call this method explicitly. It will be implicitly called by
217 :meth:`sendmail` when necessary.
218
Christian Heimes679db4a2008-01-18 09:56:22 +0000219.. method:: SMTP.ehlo_or_helo_if_needed()
220
221 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
222 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
223 first.
224
Georg Brandl1f01deb2009-01-03 22:47:39 +0000225 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000226 The server didn't reply properly to the ``HELO`` greeting.
227
Georg Brandl116aa622007-08-15 14:28:22 +0000228.. method:: SMTP.has_extn(name)
229
230 Return :const:`True` if *name* is in the set of SMTP service extensions returned
231 by the server, :const:`False` otherwise. Case is ignored.
232
233
234.. method:: SMTP.verify(address)
235
236 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
237 tuple consisting of code 250 and a full :rfc:`822` address (including human
238 name) if the user address is valid. Otherwise returns an SMTP error code of 400
239 or greater and an error string.
240
241 .. note::
242
243 Many sites disable SMTP ``VRFY`` in order to foil spammers.
244
245
246.. method:: SMTP.login(user, password)
247
248 Log in on an SMTP server that requires authentication. The arguments are the
249 username and the password to authenticate with. If there has been no previous
250 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
251 first. This method will return normally if the authentication was successful, or
252 may raise the following exceptions:
253
254 :exc:`SMTPHeloError`
255 The server didn't reply properly to the ``HELO`` greeting.
256
257 :exc:`SMTPAuthenticationError`
258 The server didn't accept the username/password combination.
259
260 :exc:`SMTPException`
261 No suitable authentication method was found.
262
263
Antoine Pitroue0650202011-05-18 18:03:09 +0200264.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
267 commands that follow will be encrypted. You should then call :meth:`ehlo`
268 again.
269
270 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
271 module's :func:`ssl` function.
272
Antoine Pitroue0650202011-05-18 18:03:09 +0200273 Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
274 using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
275
Christian Heimes679db4a2008-01-18 09:56:22 +0000276 If there has been no previous ``EHLO`` or ``HELO`` command this session,
277 this method tries ESMTP ``EHLO`` first.
278
Christian Heimes679db4a2008-01-18 09:56:22 +0000279 :exc:`SMTPHeloError`
280 The server didn't reply properly to the ``HELO`` greeting.
281
282 :exc:`SMTPException`
283 The server does not support the STARTTLS extension.
284
Christian Heimes679db4a2008-01-18 09:56:22 +0000285 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000286 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000287
Antoine Pitroue0650202011-05-18 18:03:09 +0200288 .. versionchanged:: 3.3
289 *context* was added.
290
Georg Brandl116aa622007-08-15 14:28:22 +0000291
Georg Brandl18244152009-09-02 20:34:52 +0000292.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294 Send mail. The required arguments are an :rfc:`822` from-address string, a list
295 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
296 address), and a message string. The caller may pass a list of ESMTP options
297 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
298 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
299 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
300 options to different recipients you have to use the low-level methods such as
301 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
302
303 .. note::
304
305 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000306 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000307 message headers in any way.
308
R. David Murray7dff9e02010-11-08 17:15:13 +0000309 msg may be a string containing characters in the ASCII range, or a byte
310 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
311 and ``\n`` characters are converted to ``\r\n`` characters. A byte string
312 is not modified.
313
Georg Brandl116aa622007-08-15 14:28:22 +0000314 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
315 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
316 each of the specified options will be passed to it (if the option is in the
317 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
318 and ESMTP options suppressed.
319
320 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000321 recipient. Otherwise it will raise an exception. That is, if this method does
322 not raise an exception, then someone should get your mail. If this method does
323 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000324 recipient that was refused. Each entry contains a tuple of the SMTP error code
325 and the accompanying error message sent by the server.
326
327 This method may raise the following exceptions:
328
329 :exc:`SMTPRecipientsRefused`
330 All recipients were refused. Nobody got the mail. The :attr:`recipients`
331 attribute of the exception object is a dictionary with information about the
332 refused recipients (like the one returned when at least one recipient was
333 accepted).
334
335 :exc:`SMTPHeloError`
336 The server didn't reply properly to the ``HELO`` greeting.
337
338 :exc:`SMTPSenderRefused`
339 The server didn't accept the *from_addr*.
340
341 :exc:`SMTPDataError`
342 The server replied with an unexpected error code (other than a refusal of a
343 recipient).
344
345 Unless otherwise noted, the connection will be open even after an exception is
346 raised.
347
R. David Murray7dff9e02010-11-08 17:15:13 +0000348 .. versionchanged:: 3.2 *msg* may be a byte string.
349
350
351.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=[], rcpt_options=[])
352
353 This is a convenience method for calling :meth:`sendmail` with the message
354 represented by an :class:`email.message.Message` object. The arguments have
355 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
356 object.
357
358 If *from_addr* is ``None``, ``send_message`` sets its value to the value of
359 the :mailheader:`From` header from *msg*. If *to_addrs* is ``None``,
360 ``send_message`` combines the values (if any) of the :mailheader:`To`,
361 :mailheader:`CC`, and :mailheader:`Bcc` fields from *msg*. Regardless of
362 the values of *from_addr* and *to_addrs*, ``send_message`` deletes any Bcc
363 field from *msg*. It then serializes *msg* using
364 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
365 calls :meth:`sendmail` to transmit the resulting message.
366
367 .. versionadded:: 3.2
368
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370.. method:: SMTP.quit()
371
Christian Heimesba4af492008-03-28 00:55:15 +0000372 Terminate the SMTP session and close the connection. Return the result of
373 the SMTP ``QUIT`` command.
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
377``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
378Normally these do not need to be called directly, so they are not documented
379here. For details, consult the module code.
380
381
382.. _smtp-example:
383
384SMTP Example
385------------
386
387This example prompts the user for addresses needed in the message envelope ('To'
388and 'From' addresses), and the message to be delivered. Note that the headers
389to be included with the message must be included in the message as entered; this
390example doesn't do any processing of the :rfc:`822` headers. In particular, the
391'To' and 'From' addresses must be included in the message headers explicitly. ::
392
393 import smtplib
394
Georg Brandl116aa622007-08-15 14:28:22 +0000395 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000396 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398 fromaddr = prompt("From: ")
399 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000400 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 # Add the From: and To: headers at the start!
403 msg = ("From: %s\r\nTo: %s\r\n\r\n"
404 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000405 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000406 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000407 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000408 except EOFError:
409 break
410 if not line:
411 break
412 msg = msg + line
413
Georg Brandl6911e3c2007-09-04 07:15:32 +0000414 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416 server = smtplib.SMTP('localhost')
417 server.set_debuglevel(1)
418 server.sendmail(fromaddr, toaddrs, msg)
419 server.quit()
420
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000421.. note::
422
423 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000424 construct an email message, which you can then send
425 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.