blob: 602edb6a3f144dba6809729f411805cc5a718ea3 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`smtplib` --- SMTP protocol client
3=======================================
4
5.. module:: smtplib
6 :synopsis: SMTP protocol client (requires sockets).
7.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
8
9
10.. index::
11 pair: SMTP; protocol
12 single: Simple Mail Transfer Protocol
13
14The :mod:`smtplib` module defines an SMTP client session object that can be used
15to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For
16details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
17Protocol) and :rfc:`1869` (SMTP Service Extensions).
18
19
20.. class:: SMTP([host[, port[, local_hostname[, timeout]]]])
21
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000022 A :class:`SMTP` instance encapsulates an SMTP connection. It has methods
23 that support a full repertoire of SMTP and ESMTP operations. If the optional
24 host and port parameters are given, the SMTP :meth:`connect` method is called
25 with those parameters during initialization. An :exc:`SMTPConnectError` is
26 raised if the specified host doesn't respond correctly. The optional
27 *timeout* parameter specifies a timeout in seconds for blocking operations
28 like the connection attempt (if not specified, or passed as None, the global
29 default timeout setting will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 For normal use, you should only require the initialization/connect,
32 :meth:`sendmail`, and :meth:`quit` methods. An example is included below.
33
Georg Brandl116aa622007-08-15 14:28:22 +000034
35.. class:: SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])
36
37 A :class:`SMTP_SSL` instance behaves exactly the same as instances of
38 :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000039 required from the beginning of the connection and using :meth:`starttls` is
40 not appropriate. If *host* is not specified, the local host is used. If
41 *port* is omitted, the standard SMTP-over-SSL port (465) is used. *keyfile*
42 and *certfile* are also optional, and can contain a PEM formatted private key
43 and certificate chain file for the SSL connection. The optional *timeout*
44 parameter specifies a timeout in seconds for blocking operations like the
45 connection attempt (if not specified, or passed as None, the global default
46 timeout setting will be used).
Georg Brandl116aa622007-08-15 14:28:22 +000047
Georg Brandl116aa622007-08-15 14:28:22 +000048
49.. class:: LMTP([host[, port[, local_hostname]]])
50
51 The LMTP protocol, which is very similar to ESMTP, is heavily based on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000052 standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect`
Georg Brandl116aa622007-08-15 14:28:22 +000053 method must support that as well as a regular host:port server. To specify a
54 Unix socket, you must use an absolute path for *host*, starting with a '/'.
55
56 Authentication is supported, using the regular SMTP mechanism. When using a Unix
57 socket, LMTP generally don't support or require any authentication, but your
58 mileage might vary.
59
Georg Brandl116aa622007-08-15 14:28:22 +000060
61A nice selection of exceptions is defined as well:
62
63
64.. exception:: SMTPException
65
66 Base exception class for all exceptions raised by this module.
67
68
69.. exception:: SMTPServerDisconnected
70
71 This exception is raised when the server unexpectedly disconnects, or when an
72 attempt is made to use the :class:`SMTP` instance before connecting it to a
73 server.
74
75
76.. exception:: SMTPResponseException
77
78 Base class for all exceptions that include an SMTP error code. These exceptions
79 are generated in some instances when the SMTP server returns an error code. The
80 error code is stored in the :attr:`smtp_code` attribute of the error, and the
81 :attr:`smtp_error` attribute is set to the error message.
82
83
84.. exception:: SMTPSenderRefused
85
86 Sender address refused. In addition to the attributes set by on all
87 :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
88 the SMTP server refused.
89
90
91.. exception:: SMTPRecipientsRefused
92
93 All recipient addresses refused. The errors for each recipient are accessible
94 through the attribute :attr:`recipients`, which is a dictionary of exactly the
95 same sort as :meth:`SMTP.sendmail` returns.
96
97
98.. exception:: SMTPDataError
99
100 The SMTP server refused to accept the message data.
101
102
103.. exception:: SMTPConnectError
104
105 Error occurred during establishment of a connection with the server.
106
107
108.. exception:: SMTPHeloError
109
110 The server refused our ``HELO`` message.
111
112
113.. exception:: SMTPAuthenticationError
114
115 SMTP authentication went wrong. Most probably the server didn't accept the
116 username/password combination provided.
117
118
119.. seealso::
120
121 :rfc:`821` - Simple Mail Transfer Protocol
122 Protocol definition for SMTP. This document covers the model, operating
123 procedure, and protocol details for SMTP.
124
125 :rfc:`1869` - SMTP Service Extensions
126 Definition of the ESMTP extensions for SMTP. This describes a framework for
127 extending SMTP with new commands, supporting dynamic discovery of the commands
128 provided by the server, and defines a few additional commands.
129
130
131.. _smtp-objects:
132
133SMTP Objects
134------------
135
136An :class:`SMTP` instance has the following methods:
137
138
139.. method:: SMTP.set_debuglevel(level)
140
141 Set the debug output level. A true value for *level* results in debug messages
142 for connection and for all messages sent to and received from the server.
143
144
145.. method:: SMTP.connect([host[, port]])
146
147 Connect to a host on a given port. The defaults are to connect to the local
148 host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
149 followed by a number, that suffix will be stripped off and the number
150 interpreted as the port number to use. This method is automatically invoked by
151 the constructor if a host is specified during instantiation.
152
153
154.. method:: SMTP.docmd(cmd, [, argstring])
155
156 Send a command *cmd* to the server. The optional argument *argstring* is simply
157 concatenated to the command, separated by a space.
158
159 This returns a 2-tuple composed of a numeric response code and the actual
160 response line (multiline responses are joined into one long line.)
161
162 In normal operation it should not be necessary to call this method explicitly.
163 It is used to implement other methods and may be useful for testing private
164 extensions.
165
166 If the connection to the server is lost while waiting for the reply,
167 :exc:`SMTPServerDisconnected` will be raised.
168
169
170.. method:: SMTP.helo([hostname])
171
172 Identify yourself to the SMTP server using ``HELO``. The hostname argument
173 defaults to the fully qualified domain name of the local host.
174
175 In normal operation it should not be necessary to call this method explicitly.
176 It will be implicitly called by the :meth:`sendmail` when necessary.
177
178
179.. method:: SMTP.ehlo([hostname])
180
181 Identify yourself to an ESMTP server using ``EHLO``. The hostname argument
182 defaults to the fully qualified domain name of the local host. Examine the
183 response for ESMTP option and store them for use by :meth:`has_extn`.
184
185 Unless you wish to use :meth:`has_extn` before sending mail, it should not be
186 necessary to call this method explicitly. It will be implicitly called by
187 :meth:`sendmail` when necessary.
188
Christian Heimes679db4a2008-01-18 09:56:22 +0000189.. method:: SMTP.ehlo_or_helo_if_needed()
190
191 This method call :meth:`ehlo` and or :meth:`helo` if there has been no
192 previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
193 first.
194
195 :exc:SMTPHeloError
196 The server didn't reply properly to the ``HELO`` greeting.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198.. method:: SMTP.has_extn(name)
199
200 Return :const:`True` if *name* is in the set of SMTP service extensions returned
201 by the server, :const:`False` otherwise. Case is ignored.
202
203
204.. method:: SMTP.verify(address)
205
206 Check the validity of an address on this server using SMTP ``VRFY``. Returns a
207 tuple consisting of code 250 and a full :rfc:`822` address (including human
208 name) if the user address is valid. Otherwise returns an SMTP error code of 400
209 or greater and an error string.
210
211 .. note::
212
213 Many sites disable SMTP ``VRFY`` in order to foil spammers.
214
215
216.. method:: SMTP.login(user, password)
217
218 Log in on an SMTP server that requires authentication. The arguments are the
219 username and the password to authenticate with. If there has been no previous
220 ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
221 first. This method will return normally if the authentication was successful, or
222 may raise the following exceptions:
223
224 :exc:`SMTPHeloError`
225 The server didn't reply properly to the ``HELO`` greeting.
226
227 :exc:`SMTPAuthenticationError`
228 The server didn't accept the username/password combination.
229
230 :exc:`SMTPException`
231 No suitable authentication method was found.
232
233
234.. method:: SMTP.starttls([keyfile[, certfile]])
235
236 Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP
237 commands that follow will be encrypted. You should then call :meth:`ehlo`
238 again.
239
240 If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
241 module's :func:`ssl` function.
242
Christian Heimes679db4a2008-01-18 09:56:22 +0000243 If there has been no previous ``EHLO`` or ``HELO`` command this session,
244 this method tries ESMTP ``EHLO`` first.
245
Christian Heimes679db4a2008-01-18 09:56:22 +0000246 :exc:`SMTPHeloError`
247 The server didn't reply properly to the ``HELO`` greeting.
248
249 :exc:`SMTPException`
250 The server does not support the STARTTLS extension.
251
Christian Heimes679db4a2008-01-18 09:56:22 +0000252 :exc:`RuntimeError`
253 SSL/TLS support is not available to your python interpreter.
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256.. method:: SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
257
258 Send mail. The required arguments are an :rfc:`822` from-address string, a list
259 of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
260 address), and a message string. The caller may pass a list of ESMTP options
261 (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
262 ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
263 commands can be passed as *rcpt_options*. (If you need to use different ESMTP
264 options to different recipients you have to use the low-level methods such as
265 :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)
266
267 .. note::
268
269 The *from_addr* and *to_addrs* parameters are used to construct the message
270 envelope used by the transport agents. The :class:`SMTP` does not modify the
271 message headers in any way.
272
273 If there has been no previous ``EHLO`` or ``HELO`` command this session, this
274 method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
275 each of the specified options will be passed to it (if the option is in the
276 feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried
277 and ESMTP options suppressed.
278
279 This method will return normally if the mail is accepted for at least one
280 recipient. Otherwise it will throw an exception. That is, if this method does
281 not throw an exception, then someone should get your mail. If this method does
282 not throw an exception, it returns a dictionary, with one entry for each
283 recipient that was refused. Each entry contains a tuple of the SMTP error code
284 and the accompanying error message sent by the server.
285
286 This method may raise the following exceptions:
287
288 :exc:`SMTPRecipientsRefused`
289 All recipients were refused. Nobody got the mail. The :attr:`recipients`
290 attribute of the exception object is a dictionary with information about the
291 refused recipients (like the one returned when at least one recipient was
292 accepted).
293
294 :exc:`SMTPHeloError`
295 The server didn't reply properly to the ``HELO`` greeting.
296
297 :exc:`SMTPSenderRefused`
298 The server didn't accept the *from_addr*.
299
300 :exc:`SMTPDataError`
301 The server replied with an unexpected error code (other than a refusal of a
302 recipient).
303
304 Unless otherwise noted, the connection will be open even after an exception is
305 raised.
306
307
308.. method:: SMTP.quit()
309
Christian Heimesba4af492008-03-28 00:55:15 +0000310 Terminate the SMTP session and close the connection. Return the result of
311 the SMTP ``QUIT`` command.
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
315``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
316Normally these do not need to be called directly, so they are not documented
317here. For details, consult the module code.
318
319
320.. _smtp-example:
321
322SMTP Example
323------------
324
325This example prompts the user for addresses needed in the message envelope ('To'
326and 'From' addresses), and the message to be delivered. Note that the headers
327to be included with the message must be included in the message as entered; this
328example doesn't do any processing of the :rfc:`822` headers. In particular, the
329'To' and 'From' addresses must be included in the message headers explicitly. ::
330
331 import smtplib
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333 def prompt(prompt):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000334 return input(prompt).strip()
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336 fromaddr = prompt("From: ")
337 toaddrs = prompt("To: ").split()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000338 print("Enter message, end with ^D (Unix) or ^Z (Windows):")
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340 # Add the From: and To: headers at the start!
341 msg = ("From: %s\r\nTo: %s\r\n\r\n"
342 % (fromaddr, ", ".join(toaddrs)))
Collin Winter46334482007-09-10 00:49:57 +0000343 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000344 try:
Georg Brandl8d5c3922007-12-02 22:48:17 +0000345 line = input()
Georg Brandl116aa622007-08-15 14:28:22 +0000346 except EOFError:
347 break
348 if not line:
349 break
350 msg = msg + line
351
Georg Brandl6911e3c2007-09-04 07:15:32 +0000352 print("Message length is", len(msg))
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354 server = smtplib.SMTP('localhost')
355 server.set_debuglevel(1)
356 server.sendmail(fromaddr, toaddrs, msg)
357 server.quit()
358