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