blob: 3101ab7284d106a499e46198b762b610b17a30a8 [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
Georg Brandl116aa622007-08-15 14:28:22 +000037
Georg Brandl18244152009-09-02 20:34:52 +000038.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout])
Georg Brandl116aa622007-08-15 14:28:22 +000039
40 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
41 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000042 required from the beginning of the connection and using :meth:`starttls` is
43 not appropriate. If *host* is not specified, the local host is used. If
Georg Brandl18244152009-09-02 20:34:52 +000044 *port* is zero, the standard SMTP-over-SSL port (465) is used. *keyfile*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000045 and *certfile* are also optional, and can contain a PEM formatted private key
46 and certificate chain file for the SSL connection. The optional *timeout*
47 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000048 connection attempt (if not specified, the global default timeout setting
49 will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000050
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandl18244152009-09-02 20:34:52 +000052.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +000053
54 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000055 standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +000056 method must support that as well as a regular host:port server. To specify a
57 Unix socket, you must use an absolute path for *host*, starting with a '/'.
58
59 Authentication is supported, using the regular SMTP mechanism. When using a Unix
60 socket, LMTP generally don't support or require any authentication, but your
61 mileage might vary.
62
Georg Brandl116aa622007-08-15 14:28:22 +000063
64A nice selection of exceptions is defined as well:
65
66
67.. exception:: SMTPException
68
69 Base exception class for all exceptions raised by this module.
70
71
72.. exception:: SMTPServerDisconnected
73
74 This exception is raised when the server unexpectedly disconnects, or when an
75 attempt is made to use the :class:`SMTP` instance before connecting it to a
76 server.
77
78
79.. exception:: SMTPResponseException
80
81 Base class for all exceptions that include an SMTP error code. These exceptions
82 are generated in some instances when the SMTP server returns an error code. The
83 error code is stored in the :attr:`smtp_code` attribute of the error, and the
84 :attr:`smtp_error` attribute is set to the error message.
85
86
87.. exception:: SMTPSenderRefused
88
89 Sender address refused. In addition to the attributes set by on all
90 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
91 the SMTP server refused.
92
93
94.. exception:: SMTPRecipientsRefused
95
96 All recipient addresses refused. The errors for each recipient are accessible
97 through the attribute :attr:`recipients`, which is a dictionary of exactly the
98 same sort as :meth:`SMTP.sendmail` returns.
99
100
101.. exception:: SMTPDataError
102
103 The SMTP server refused to accept the message data.
104
105
106.. exception:: SMTPConnectError
107
108 Error occurred during establishment of a connection with the server.
109
110
111.. exception:: SMTPHeloError
112
113 The server refused our ``HELO`` message.
114
115
116.. exception:: SMTPAuthenticationError
117
118 SMTP authentication went wrong. Most probably the server didn't accept the
119 username/password combination provided.
120
121
122.. seealso::
123
124 :rfc:`821` - Simple Mail Transfer Protocol
125 Protocol definition for SMTP. This document covers the model, operating
126 procedure, and protocol details for SMTP.
127
128 :rfc:`1869` - SMTP Service Extensions
129 Definition of the ESMTP extensions for SMTP. This describes a framework for
130 extending SMTP with new commands, supporting dynamic discovery of the commands
131 provided by the server, and defines a few additional commands.
132
133
134.. _smtp-objects:
135
136SMTP Objects
137------------
138
139An :class:`SMTP` instance has the following methods:
140
141
142.. method:: SMTP.set_debuglevel(level)
143
144 Set the debug output level. A true value for *level* results in debug messages
145 for connection and for all messages sent to and received from the server.
146
147
Georg Brandl18244152009-09-02 20:34:52 +0000148.. method:: SMTP.connect(host='localhost', port=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150 Connect to a host on a given port. The defaults are to connect to the local
151 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
152 followed by a number, that suffix will be stripped off and the number
153 interpreted as the port number to use. This method is automatically invoked by
154 the constructor if a host is specified during instantiation.
155
156
Georg Brandl18244152009-09-02 20:34:52 +0000157.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Georg Brandl18244152009-09-02 20:34:52 +0000159 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000160 concatenated to the command, separated by a space.
161
162 This returns a 2-tuple composed of a numeric response code and the actual
163 response line (multiline responses are joined into one long line.)
164
165 In normal operation it should not be necessary to call this method explicitly.
166 It is used to implement other methods and may be useful for testing private
167 extensions.
168
169 If the connection to the server is lost while waiting for the reply,
170 :exc:`SMTPServerDisconnected` will be raised.
171
172
Georg Brandl18244152009-09-02 20:34:52 +0000173.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175 Identify yourself to the SMTP server using ``HELO``. The hostname argument
176 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000177 The message returned by the server is stored as the :attr:`helo_resp` attribute
178 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 In normal operation it should not be necessary to call this method explicitly.
181 It will be implicitly called by the :meth:`sendmail` when necessary.
182
183
Georg Brandl18244152009-09-02 20:34:52 +0000184.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
187 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000188 response for ESMTP option and store them for use by :meth:`has_extn`.
189 Also sets several informational attributes: the message returned by
190 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000191 is set to true or false depending on whether the server supports ESMTP, and
192 :attr:`esmtp_features` will be a dictionary containing the names of the
193 SMTP service extensions this server supports, and their
194 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
197 necessary to call this method explicitly. It will be implicitly called by
198 :meth:`sendmail` when necessary.
199
Christian Heimes679db4a2008-01-18 09:56:22 +0000200.. method:: SMTP.ehlo_or_helo_if_needed()
201
202 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
203 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
204 first.
205
Georg Brandl1f01deb2009-01-03 22:47:39 +0000206 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000207 The server didn't reply properly to the ``HELO`` greeting.
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209.. method:: SMTP.has_extn(name)
210
211 Return :const:`True` if *name* is in the set of SMTP service extensions returned
212 by the server, :const:`False` otherwise. Case is ignored.
213
214
215.. method:: SMTP.verify(address)
216
217 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
218 tuple consisting of code 250 and a full :rfc:`822` address (including human
219 name) if the user address is valid. Otherwise returns an SMTP error code of 400
220 or greater and an error string.
221
222 .. note::
223
224 Many sites disable SMTP ``VRFY`` in order to foil spammers.
225
226
227.. method:: SMTP.login(user, password)
228
229 Log in on an SMTP server that requires authentication. The arguments are the
230 username and the password to authenticate with. If there has been no previous
231 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
232 first. This method will return normally if the authentication was successful, or
233 may raise the following exceptions:
234
235 :exc:`SMTPHeloError`
236 The server didn't reply properly to the ``HELO`` greeting.
237
238 :exc:`SMTPAuthenticationError`
239 The server didn't accept the username/password combination.
240
241 :exc:`SMTPException`
242 No suitable authentication method was found.
243
244
Georg Brandl18244152009-09-02 20:34:52 +0000245.. method:: SMTP.starttls(keyfile=None, certfile=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
248 commands that follow will be encrypted. You should then call :meth:`ehlo`
249 again.
250
251 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
252 module's :func:`ssl` function.
253
Christian Heimes679db4a2008-01-18 09:56:22 +0000254 If there has been no previous ``EHLO`` or ``HELO`` command this session,
255 this method tries ESMTP ``EHLO`` first.
256
Christian Heimes679db4a2008-01-18 09:56:22 +0000257 :exc:`SMTPHeloError`
258 The server didn't reply properly to the ``HELO`` greeting.
259
260 :exc:`SMTPException`
261 The server does not support the STARTTLS extension.
262
Christian Heimes679db4a2008-01-18 09:56:22 +0000263 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000264 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000265
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Georg Brandl18244152009-09-02 20:34:52 +0000267.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269 Send mail. The required arguments are an :rfc:`822` from-address string, a list
270 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
271 address), and a message string. The caller may pass a list of ESMTP options
272 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
273 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
274 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
275 options to different recipients you have to use the low-level methods such as
276 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
277
278 .. note::
279
280 The *from_addr* and *to_addrs* parameters are used to construct the message
R. David Murray7dff9e02010-11-08 17:15:13 +0000281 envelope used by the transport agents. ``sendmail`` does not modify the
Georg Brandl116aa622007-08-15 14:28:22 +0000282 message headers in any way.
283
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600284 *msg* may be a string containing characters in the ASCII range, or a byte
R. David Murray7dff9e02010-11-08 17:15:13 +0000285 string. A string is encoded to bytes using the ascii codec, and lone ``\r``
Benjamin Petersona6c4a102011-12-30 23:08:09 -0600286 and ``\n`` characters are converted to ``\r\n`` characters. A byte string is
287 not modified.
R. David Murray7dff9e02010-11-08 17:15:13 +0000288
Georg Brandl116aa622007-08-15 14:28:22 +0000289 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
290 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
291 each of the specified options will be passed to it (if the option is in the
292 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
293 and ESMTP options suppressed.
294
295 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000296 recipient. Otherwise it will raise an exception. That is, if this method does
297 not raise an exception, then someone should get your mail. If this method does
298 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000299 recipient that was refused. Each entry contains a tuple of the SMTP error code
300 and the accompanying error message sent by the server.
301
302 This method may raise the following exceptions:
303
304 :exc:`SMTPRecipientsRefused`
305 All recipients were refused. Nobody got the mail. The :attr:`recipients`
306 attribute of the exception object is a dictionary with information about the
307 refused recipients (like the one returned when at least one recipient was
308 accepted).
309
310 :exc:`SMTPHeloError`
311 The server didn't reply properly to the ``HELO`` greeting.
312
313 :exc:`SMTPSenderRefused`
314 The server didn't accept the *from_addr*.
315
316 :exc:`SMTPDataError`
317 The server replied with an unexpected error code (other than a refusal of a
318 recipient).
319
320 Unless otherwise noted, the connection will be open even after an exception is
321 raised.
322
R. David Murray7dff9e02010-11-08 17:15:13 +0000323 .. versionchanged:: 3.2 *msg* may be a byte string.
324
325
R David Murrayac4e5ab2011-07-02 21:03:19 -0400326.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \
327 mail_options=[], rcpt_options=[])
R. David Murray7dff9e02010-11-08 17:15:13 +0000328
329 This is a convenience method for calling :meth:`sendmail` with the message
330 represented by an :class:`email.message.Message` object. The arguments have
331 the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message``
332 object.
333
R David Murrayac4e5ab2011-07-02 21:03:19 -0400334 If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills
335 those arguments with addresses extracted from the headers of *msg* as
336 specified in :rfc:`2822`\: *from_addr* is set to the :mailheader:`Sender`
337 field if it is present, and otherwise to the :mailheader:`From` field.
338 *to_adresses* combines the values (if any) of the :mailheader:`To`,
339 :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one
340 set of :mailheader:`Resent-*` headers appear in the message, the regular
341 headers are ignored and the :mailheader:`Resent-*` headers are used instead.
342 If the message contains more than one set of :mailheader:`Resent-*` headers,
343 a :exc:`ValueError` is raised, since there is no way to unambiguously detect
344 the most recent set of :mailheader:`Resent-` headers.
345
346 ``send_message`` serializes *msg* using
R. David Murray7dff9e02010-11-08 17:15:13 +0000347 :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and
R David Murrayac4e5ab2011-07-02 21:03:19 -0400348 calls :meth:`sendmail` to transmit the resulting message. Regardless of the
349 values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any
350 :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear
351 in *msg*.
R. David Murray7dff9e02010-11-08 17:15:13 +0000352
353 .. versionadded:: 3.2
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356.. method:: SMTP.quit()
357
Christian Heimesba4af492008-03-28 00:55:15 +0000358 Terminate the SMTP session and close the connection. Return the result of
359 the SMTP ``QUIT`` command.
360
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
363``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
364Normally these do not need to be called directly, so they are not documented
365here. For details, consult the module code.
366
367
368.. _smtp-example:
369
370SMTP Example
371------------
372
373This example prompts the user for addresses needed in the message envelope ('To'
374and 'From' addresses), and the message to be delivered. Note that the headers
375to be included with the message must be included in the message as entered; this
376example doesn't do any processing of the :rfc:`822` headers. In particular, the
377'To' and 'From' addresses must be included in the message headers explicitly. ::
378
379 import smtplib
380
Georg Brandl116aa622007-08-15 14:28:22 +0000381 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000382 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384 fromaddr = prompt("From: ")
385 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000386 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388 # Add the From: and To: headers at the start!
389 msg = ("From: %s\r\nTo: %s\r\n\r\n"
390 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000391 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000392 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000393 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000394 except EOFError:
395 break
396 if not line:
397 break
398 msg = msg + line
399
Georg Brandl6911e3c2007-09-04 07:15:32 +0000400 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 server = smtplib.SMTP('localhost')
403 server.set_debuglevel(1)
404 server.sendmail(fromaddr, toaddrs, msg)
405 server.quit()
406
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000407.. note::
408
409 In general, you will want to use the :mod:`email` package's features to
R. David Murray7dff9e02010-11-08 17:15:13 +0000410 construct an email message, which you can then send
411 via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`.