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