blob: cfd5018a999c6498ef3de651aa1f05dd5125d376 [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
Georg Brandl18244152009-09-02 20:34:52 +000052.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout])
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
60 and certificate chain file for the SSL connection. The optional *timeout*
61 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000062 connection attempt (if not specified, the global default timeout setting
63 will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000064
Georg Brandl116aa622007-08-15 14:28:22 +000065
Georg Brandl18244152009-09-02 20:34:52 +000066.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000069 standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +000070 method must support that as well as a regular host:port server. To specify a
71 Unix socket, you must use an absolute path for *host*, starting with a '/'.
72
73 Authentication is supported, using the regular SMTP mechanism. When using a Unix
74 socket, LMTP generally don't support or require any authentication, but your
75 mileage might vary.
76
Georg Brandl116aa622007-08-15 14:28:22 +000077
78A nice selection of exceptions is defined as well:
79
80
81.. exception:: SMTPException
82
83 Base exception class for all exceptions raised by this module.
84
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 Brandl18244152009-09-02 20:34:52 +0000162.. method:: SMTP.connect(host='localhost', port=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164 Connect to a host on a given port. The defaults are to connect to the local
165 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
166 followed by a number, that suffix will be stripped off and the number
167 interpreted as the port number to use. This method is automatically invoked by
168 the constructor if a host is specified during instantiation.
169
170
Georg Brandl18244152009-09-02 20:34:52 +0000171.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Georg Brandl18244152009-09-02 20:34:52 +0000173 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000174 concatenated to the command, separated by a space.
175
176 This returns a 2-tuple composed of a numeric response code and the actual
177 response line (multiline responses are joined into one long line.)
178
179 In normal operation it should not be necessary to call this method explicitly.
180 It is used to implement other methods and may be useful for testing private
181 extensions.
182
183 If the connection to the server is lost while waiting for the reply,
184 :exc:`SMTPServerDisconnected` will be raised.
185
186
Georg Brandl18244152009-09-02 20:34:52 +0000187.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 Identify yourself to the SMTP server using ``HELO``. The hostname argument
190 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000191 The message returned by the server is stored as the :attr:`helo_resp` attribute
192 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194 In normal operation it should not be necessary to call this method explicitly.
195 It will be implicitly called by the :meth:`sendmail` when necessary.
196
197
Georg Brandl18244152009-09-02 20:34:52 +0000198.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
201 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000202 response for ESMTP option and store them for use by :meth:`has_extn`.
203 Also sets several informational attributes: the message returned by
204 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000205 is set to true or false depending on whether the server supports ESMTP, and
206 :attr:`esmtp_features` will be a dictionary containing the names of the
207 SMTP service extensions this server supports, and their
208 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
211 necessary to call this method explicitly. It will be implicitly called by
212 :meth:`sendmail` when necessary.
213
Christian Heimes679db4a2008-01-18 09:56:22 +0000214.. method:: SMTP.ehlo_or_helo_if_needed()
215
216 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
217 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
218 first.
219
Georg Brandl1f01deb2009-01-03 22:47:39 +0000220 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000221 The server didn't reply properly to the ``HELO`` greeting.
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223.. method:: SMTP.has_extn(name)
224
225 Return :const:`True` if *name* is in the set of SMTP service extensions returned
226 by the server, :const:`False` otherwise. Case is ignored.
227
228
229.. method:: SMTP.verify(address)
230
231 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
232 tuple consisting of code 250 and a full :rfc:`822` address (including human
233 name) if the user address is valid. Otherwise returns an SMTP error code of 400
234 or greater and an error string.
235
236 .. note::
237
238 Many sites disable SMTP ``VRFY`` in order to foil spammers.
239
240
241.. method:: SMTP.login(user, password)
242
243 Log in on an SMTP server that requires authentication. The arguments are the
244 username and the password to authenticate with. If there has been no previous
245 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
246 first. This method will return normally if the authentication was successful, or
247 may raise the following exceptions:
248
249 :exc:`SMTPHeloError`
250 The server didn't reply properly to the ``HELO`` greeting.
251
252 :exc:`SMTPAuthenticationError`
253 The server didn't accept the username/password combination.
254
255 :exc:`SMTPException`
256 No suitable authentication method was found.
257
258
Georg Brandl18244152009-09-02 20:34:52 +0000259.. method:: SMTP.starttls(keyfile=None, certfile=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
262 commands that follow will be encrypted. You should then call :meth:`ehlo`
263 again.
264
265 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
266 module's :func:`ssl` function.
267
Christian Heimes679db4a2008-01-18 09:56:22 +0000268 If there has been no previous ``EHLO`` or ``HELO`` command this session,
269 this method tries ESMTP ``EHLO`` first.
270
Christian Heimes679db4a2008-01-18 09:56:22 +0000271 :exc:`SMTPHeloError`
272 The server didn't reply properly to the ``HELO`` greeting.
273
274 :exc:`SMTPException`
275 The server does not support the STARTTLS extension.
276
Christian Heimes679db4a2008-01-18 09:56:22 +0000277 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000278 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000279
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Georg Brandl18244152009-09-02 20:34:52 +0000281.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 Send mail. The required arguments are an :rfc:`822` from-address string, a list
284 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
285 address), and a message string. The caller may pass a list of ESMTP options
286 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
287 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
288 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
289 options to different recipients you have to use the low-level methods such as
290 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
291
292 .. note::
293
294 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000295 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000296 message headers in any way.
297
R. David Murray7dff9e02010-11-08 17:15:13 +0000298 msg may be a string containing characters in the ASCII range, or a byte
299 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
300 and ``\n`` characters are converted to ``\r\n`` characters. A byte string
301 is not modified.
302
Georg Brandl116aa622007-08-15 14:28:22 +0000303 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
304 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
305 each of the specified options will be passed to it (if the option is in the
306 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
307 and ESMTP options suppressed.
308
309 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000310 recipient. Otherwise it will raise an exception. That is, if this method does
311 not raise an exception, then someone should get your mail. If this method does
312 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000313 recipient that was refused. Each entry contains a tuple of the SMTP error code
314 and the accompanying error message sent by the server.
315
316 This method may raise the following exceptions:
317
318 :exc:`SMTPRecipientsRefused`
319 All recipients were refused. Nobody got the mail. The :attr:`recipients`
320 attribute of the exception object is a dictionary with information about the
321 refused recipients (like the one returned when at least one recipient was
322 accepted).
323
324 :exc:`SMTPHeloError`
325 The server didn't reply properly to the ``HELO`` greeting.
326
327 :exc:`SMTPSenderRefused`
328 The server didn't accept the *from_addr*.
329
330 :exc:`SMTPDataError`
331 The server replied with an unexpected error code (other than a refusal of a
332 recipient).
333
334 Unless otherwise noted, the connection will be open even after an exception is
335 raised.
336
R. David Murray7dff9e02010-11-08 17:15:13 +0000337 .. versionchanged:: 3.2 *msg* may be a byte string.
338
339
340.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=[], rcpt_options=[])
341
342 This is a convenience method for calling :meth:`sendmail` with the message
343 represented by an :class:`email.message.Message` object. The arguments have
344 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
345 object.
346
347 If *from_addr* is ``None``, ``send_message`` sets its value to the value of
348 the :mailheader:`From` header from *msg*. If *to_addrs* is ``None``,
349 ``send_message`` combines the values (if any) of the :mailheader:`To`,
350 :mailheader:`CC`, and :mailheader:`Bcc` fields from *msg*. Regardless of
351 the values of *from_addr* and *to_addrs*, ``send_message`` deletes any Bcc
352 field from *msg*. It then serializes *msg* using
353 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
354 calls :meth:`sendmail` to transmit the resulting message.
355
356 .. versionadded:: 3.2
357
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359.. method:: SMTP.quit()
360
Christian Heimesba4af492008-03-28 00:55:15 +0000361 Terminate the SMTP session and close the connection. Return the result of
362 the SMTP ``QUIT`` command.
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
366``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
367Normally these do not need to be called directly, so they are not documented
368here. For details, consult the module code.
369
370
371.. _smtp-example:
372
373SMTP Example
374------------
375
376This example prompts the user for addresses needed in the message envelope ('To'
377and 'From' addresses), and the message to be delivered. Note that the headers
378to be included with the message must be included in the message as entered; this
379example doesn't do any processing of the :rfc:`822` headers. In particular, the
380'To' and 'From' addresses must be included in the message headers explicitly. ::
381
382 import smtplib
383
Georg Brandl116aa622007-08-15 14:28:22 +0000384 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000385 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387 fromaddr = prompt("From: ")
388 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000389 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 # Add the From: and To: headers at the start!
392 msg = ("From: %s\r\nTo: %s\r\n\r\n"
393 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000394 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000395 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000396 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000397 except EOFError:
398 break
399 if not line:
400 break
401 msg = msg + line
402
Georg Brandl6911e3c2007-09-04 07:15:32 +0000403 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405 server = smtplib.SMTP('localhost')
406 server.set_debuglevel(1)
407 server.sendmail(fromaddr, toaddrs, msg)
408 server.quit()
409
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000410.. note::
411
412 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000413 construct an email message, which you can then send
414 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.