blob: 0c65290215008c05464458ff4191cbc17c95ac12 [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
13The :mod:`smtplib` module defines an SMTP client session object that can be used
14to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For
15details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
16Protocol) and :rfc:`1869` (SMTP Service Extensions).
17
18
Georg Brandl18244152009-09-02 20:34:52 +000019.. class:: SMTP(host='', port=0, local_hostname=None[, timeout])
Georg Brandl116aa622007-08-15 14:28:22 +000020
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000021 A :class:`SMTP` instance encapsulates an SMTP connection. It has methods
22 that support a full repertoire of SMTP and ESMTP operations. If the optional
23 host and port parameters are given, the SMTP :meth:`connect` method is called
24 with those parameters during initialization. An :exc:`SMTPConnectError` is
25 raised if the specified host doesn't respond correctly. The optional
26 *timeout* parameter specifies a timeout in seconds for blocking operations
Georg Brandlf78e02b2008-06-10 17:40:04 +000027 like the connection attempt (if not specified, the global default timeout
28 setting will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000029
30 For normal use, you should only require the initialization/connect,
31 :meth:`sendmail`, and :meth:`quit` methods. An example is included below.
32
Georg Brandl116aa622007-08-15 14:28:22 +000033
Georg Brandl18244152009-09-02 20:34:52 +000034.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout])
Georg Brandl116aa622007-08-15 14:28:22 +000035
36 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
37 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000038 required from the beginning of the connection and using :meth:`starttls` is
39 not appropriate. If *host* is not specified, the local host is used. If
Georg Brandl18244152009-09-02 20:34:52 +000040 *port* is zero, the standard SMTP-over-SSL port (465) is used. *keyfile*
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000041 and *certfile* are also optional, and can contain a PEM formatted private key
42 and certificate chain file for the SSL connection. The optional *timeout*
43 parameter specifies a timeout in seconds for blocking operations like the
Georg Brandlf78e02b2008-06-10 17:40:04 +000044 connection attempt (if not specified, the global default timeout setting
45 will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000046
Georg Brandl116aa622007-08-15 14:28:22 +000047
Georg Brandl18244152009-09-02 20:34:52 +000048.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +000049
50 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000051 standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +000052 method must support that as well as a regular host:port server. To specify a
53 Unix socket, you must use an absolute path for *host*, starting with a '/'.
54
55 Authentication is supported, using the regular SMTP mechanism. When using a Unix
56 socket, LMTP generally don't support or require any authentication, but your
57 mileage might vary.
58
Georg Brandl116aa622007-08-15 14:28:22 +000059
60A nice selection of exceptions is defined as well:
61
62
63.. exception:: SMTPException
64
65 Base exception class for all exceptions raised by this module.
66
67
68.. exception:: SMTPServerDisconnected
69
70 This exception is raised when the server unexpectedly disconnects, or when an
71 attempt is made to use the :class:`SMTP` instance before connecting it to a
72 server.
73
74
75.. exception:: SMTPResponseException
76
77 Base class for all exceptions that include an SMTP error code. These exceptions
78 are generated in some instances when the SMTP server returns an error code. The
79 error code is stored in the :attr:`smtp_code` attribute of the error, and the
80 :attr:`smtp_error` attribute is set to the error message.
81
82
83.. exception:: SMTPSenderRefused
84
85 Sender address refused. In addition to the attributes set by on all
86 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
87 the SMTP server refused.
88
89
90.. exception:: SMTPRecipientsRefused
91
92 All recipient addresses refused. The errors for each recipient are accessible
93 through the attribute :attr:`recipients`, which is a dictionary of exactly the
94 same sort as :meth:`SMTP.sendmail` returns.
95
96
97.. exception:: SMTPDataError
98
99 The SMTP server refused to accept the message data.
100
101
102.. exception:: SMTPConnectError
103
104 Error occurred during establishment of a connection with the server.
105
106
107.. exception:: SMTPHeloError
108
109 The server refused our ``HELO`` message.
110
111
112.. exception:: SMTPAuthenticationError
113
114 SMTP authentication went wrong. Most probably the server didn't accept the
115 username/password combination provided.
116
117
118.. seealso::
119
120 :rfc:`821` - Simple Mail Transfer Protocol
121 Protocol definition for SMTP. This document covers the model, operating
122 procedure, and protocol details for SMTP.
123
124 :rfc:`1869` - SMTP Service Extensions
125 Definition of the ESMTP extensions for SMTP. This describes a framework for
126 extending SMTP with new commands, supporting dynamic discovery of the commands
127 provided by the server, and defines a few additional commands.
128
129
130.. _smtp-objects:
131
132SMTP Objects
133------------
134
135An :class:`SMTP` instance has the following methods:
136
137
138.. method:: SMTP.set_debuglevel(level)
139
140 Set the debug output level. A true value for *level* results in debug messages
141 for connection and for all messages sent to and received from the server.
142
143
Georg Brandl18244152009-09-02 20:34:52 +0000144.. method:: SMTP.connect(host='localhost', port=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 Connect to a host on a given port. The defaults are to connect to the local
147 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
148 followed by a number, that suffix will be stripped off and the number
149 interpreted as the port number to use. This method is automatically invoked by
150 the constructor if a host is specified during instantiation.
151
152
Georg Brandl18244152009-09-02 20:34:52 +0000153.. method:: SMTP.docmd(cmd, args='')
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Georg Brandl18244152009-09-02 20:34:52 +0000155 Send a command *cmd* to the server. The optional argument *args* is simply
Georg Brandl116aa622007-08-15 14:28:22 +0000156 concatenated to the command, separated by a space.
157
158 This returns a 2-tuple composed of a numeric response code and the actual
159 response line (multiline responses are joined into one long line.)
160
161 In normal operation it should not be necessary to call this method explicitly.
162 It is used to implement other methods and may be useful for testing private
163 extensions.
164
165 If the connection to the server is lost while waiting for the reply,
166 :exc:`SMTPServerDisconnected` will be raised.
167
168
Georg Brandl18244152009-09-02 20:34:52 +0000169.. method:: SMTP.helo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171 Identify yourself to the SMTP server using ``HELO``. The hostname argument
172 defaults to the fully qualified domain name of the local host.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000173 The message returned by the server is stored as the :attr:`helo_resp` attribute
174 of the object.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176 In normal operation it should not be necessary to call this method explicitly.
177 It will be implicitly called by the :meth:`sendmail` when necessary.
178
179
Georg Brandl18244152009-09-02 20:34:52 +0000180.. method:: SMTP.ehlo(name='')
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
183 defaults to the fully qualified domain name of the local host. Examine the
Georg Brandl48310cd2009-01-03 21:18:54 +0000184 response for ESMTP option and store them for use by :meth:`has_extn`.
185 Also sets several informational attributes: the message returned by
186 the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000187 is set to true or false depending on whether the server supports ESMTP, and
188 :attr:`esmtp_features` will be a dictionary containing the names of the
189 SMTP service extensions this server supports, and their
190 parameters (if any).
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
193 necessary to call this method explicitly. It will be implicitly called by
194 :meth:`sendmail` when necessary.
195
Christian Heimes679db4a2008-01-18 09:56:22 +0000196.. method:: SMTP.ehlo_or_helo_if_needed()
197
198 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
199 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
200 first.
201
Georg Brandl1f01deb2009-01-03 22:47:39 +0000202 :exc:`SMTPHeloError`
Christian Heimes679db4a2008-01-18 09:56:22 +0000203 The server didn't reply properly to the ``HELO`` greeting.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205.. method:: SMTP.has_extn(name)
206
207 Return :const:`True` if *name* is in the set of SMTP service extensions returned
208 by the server, :const:`False` otherwise. Case is ignored.
209
210
211.. method:: SMTP.verify(address)
212
213 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
214 tuple consisting of code 250 and a full :rfc:`822` address (including human
215 name) if the user address is valid. Otherwise returns an SMTP error code of 400
216 or greater and an error string.
217
218 .. note::
219
220 Many sites disable SMTP ``VRFY`` in order to foil spammers.
221
222
223.. method:: SMTP.login(user, password)
224
225 Log in on an SMTP server that requires authentication. The arguments are the
226 username and the password to authenticate with. If there has been no previous
227 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
228 first. This method will return normally if the authentication was successful, or
229 may raise the following exceptions:
230
231 :exc:`SMTPHeloError`
232 The server didn't reply properly to the ``HELO`` greeting.
233
234 :exc:`SMTPAuthenticationError`
235 The server didn't accept the username/password combination.
236
237 :exc:`SMTPException`
238 No suitable authentication method was found.
239
240
Georg Brandl18244152009-09-02 20:34:52 +0000241.. method:: SMTP.starttls(keyfile=None, certfile=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
244 commands that follow will be encrypted. You should then call :meth:`ehlo`
245 again.
246
247 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
248 module's :func:`ssl` function.
249
Christian Heimes679db4a2008-01-18 09:56:22 +0000250 If there has been no previous ``EHLO`` or ``HELO`` command this session,
251 this method tries ESMTP ``EHLO`` first.
252
Christian Heimes679db4a2008-01-18 09:56:22 +0000253 :exc:`SMTPHeloError`
254 The server didn't reply properly to the ``HELO`` greeting.
255
256 :exc:`SMTPException`
257 The server does not support the STARTTLS extension.
258
Christian Heimes679db4a2008-01-18 09:56:22 +0000259 :exc:`RuntimeError`
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000260 SSL/TLS support is not available to your Python interpreter.
Christian Heimes679db4a2008-01-18 09:56:22 +0000261
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Georg Brandl18244152009-09-02 20:34:52 +0000263.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265 Send mail. The required arguments are an :rfc:`822` from-address string, a list
266 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
267 address), and a message string. The caller may pass a list of ESMTP options
268 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
269 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
270 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
271 options to different recipients you have to use the low-level methods such as
272 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
273
274 .. note::
275
276 The *from_addr* and *to_addrs* parameters are used to construct the message
277 envelope used by the transport agents. The :class:`SMTP` does not modify the
278 message headers in any way.
279
280 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
281 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
282 each of the specified options will be passed to it (if the option is in the
283 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
284 and ESMTP options suppressed.
285
286 This method will return normally if the mail is accepted for at least one
Georg Brandl7cb13192010-08-03 12:06:29 +0000287 recipient. Otherwise it will raise an exception. That is, if this method does
288 not raise an exception, then someone should get your mail. If this method does
289 not raise an exception, it returns a dictionary, with one entry for each
Georg Brandl116aa622007-08-15 14:28:22 +0000290 recipient that was refused. Each entry contains a tuple of the SMTP error code
291 and the accompanying error message sent by the server.
292
293 This method may raise the following exceptions:
294
295 :exc:`SMTPRecipientsRefused`
296 All recipients were refused. Nobody got the mail. The :attr:`recipients`
297 attribute of the exception object is a dictionary with information about the
298 refused recipients (like the one returned when at least one recipient was
299 accepted).
300
301 :exc:`SMTPHeloError`
302 The server didn't reply properly to the ``HELO`` greeting.
303
304 :exc:`SMTPSenderRefused`
305 The server didn't accept the *from_addr*.
306
307 :exc:`SMTPDataError`
308 The server replied with an unexpected error code (other than a refusal of a
309 recipient).
310
311 Unless otherwise noted, the connection will be open even after an exception is
312 raised.
313
314
315.. method:: SMTP.quit()
316
Christian Heimesba4af492008-03-28 00:55:15 +0000317 Terminate the SMTP session and close the connection. Return the result of
318 the SMTP ``QUIT`` command.
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
322``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
323Normally these do not need to be called directly, so they are not documented
324here. For details, consult the module code.
325
326
327.. _smtp-example:
328
329SMTP Example
330------------
331
332This example prompts the user for addresses needed in the message envelope ('To'
333and 'From' addresses), and the message to be delivered. Note that the headers
334to be included with the message must be included in the message as entered; this
335example doesn't do any processing of the :rfc:`822` headers. In particular, the
336'To' and 'From' addresses must be included in the message headers explicitly. ::
337
338 import smtplib
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000341 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343 fromaddr = prompt("From: ")
344 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000345 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347 # Add the From: and To: headers at the start!
348 msg = ("From: %s\r\nTo: %s\r\n\r\n"
349 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000350 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000351 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000352 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000353 except EOFError:
354 break
355 if not line:
356 break
357 msg = msg + line
358
Georg Brandl6911e3c2007-09-04 07:15:32 +0000359 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361 server = smtplib.SMTP('localhost')
362 server.set_debuglevel(1)
363 server.sendmail(fromaddr, toaddrs, msg)
364 server.quit()
365
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000366.. note::
367
368 In general, you will want to use the :mod:`email` package's features to
369 construct an email message, which you can then convert to a string and send
370 via :meth:`sendmail`; see :ref:`email-examples`.