• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`smtpd` --- SMTP Server
2============================
3
4.. module:: smtpd
5   :synopsis: A SMTP server implementation in Python.
6
7.. moduleauthor:: Barry Warsaw <barry@python.org>
8.. sectionauthor:: Moshe Zadka <moshez@moshez.org>
9
10**Source code:** :source:`Lib/smtpd.py`
11
12--------------
13
14This module offers several classes to implement SMTP (email) servers.
15
16.. deprecated:: 3.6
17   The `aiosmtpd <https://aiosmtpd.readthedocs.io/>`_ package is a recommended
18   replacement for this module.  It is based on :mod:`asyncio` and provides a
19   more straightforward API.
20
21Several server implementations are present; one is a generic
22do-nothing implementation, which can be overridden, while the other two offer
23specific mail-sending strategies.
24
25Additionally the SMTPChannel may be extended to implement very specific
26interaction behaviour with SMTP clients.
27
28The code supports :RFC:`5321`, plus the :rfc:`1870` SIZE and :rfc:`6531`
29SMTPUTF8 extensions.
30
31
32SMTPServer Objects
33------------------
34
35
36.. class:: SMTPServer(localaddr, remoteaddr, data_size_limit=33554432,\
37                      map=None, enable_SMTPUTF8=False, decode_data=False)
38
39   Create a new :class:`SMTPServer` object, which binds to local address
40   *localaddr*.  It will treat *remoteaddr* as an upstream SMTP relayer.  Both
41   *localaddr* and *remoteaddr* should be a :ref:`(host, port) <host_port>`
42   tuple.  The object inherits from :class:`asyncore.dispatcher`, and so will
43   insert itself into :mod:`asyncore`'s event loop on instantiation.
44
45   *data_size_limit* specifies the maximum number of bytes that will be
46   accepted in a ``DATA`` command.  A value of ``None`` or ``0`` means no
47   limit.
48
49   *map* is the socket map to use for connections (an initially empty
50   dictionary is a suitable value).  If not specified the :mod:`asyncore`
51   global socket map is used.
52
53   *enable_SMTPUTF8* determines whether the ``SMTPUTF8`` extension (as defined
54   in :RFC:`6531`) should be enabled.  The default is ``False``.
55   When ``True``, ``SMTPUTF8`` is accepted as a parameter to the ``MAIL``
56   command and when present is passed to :meth:`process_message` in the
57   ``kwargs['mail_options']`` list.  *decode_data* and *enable_SMTPUTF8*
58   cannot be set to ``True`` at the same time.
59
60   *decode_data* specifies whether the data portion of the SMTP transaction
61   should be decoded using UTF-8.  When *decode_data* is ``False`` (the
62   default), the server advertises the ``8BITMIME``
63   extension (:rfc:`6152`), accepts the ``BODY=8BITMIME`` parameter to
64   the ``MAIL`` command, and when present passes it to :meth:`process_message`
65   in the ``kwargs['mail_options']`` list. *decode_data* and *enable_SMTPUTF8*
66   cannot be set to ``True`` at the same time.
67
68   .. method:: process_message(peer, mailfrom, rcpttos, data, **kwargs)
69
70      Raise a :exc:`NotImplementedError` exception. Override this in subclasses to
71      do something useful with this message. Whatever was passed in the
72      constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
73      attribute. *peer* is the remote host's address, *mailfrom* is the envelope
74      originator, *rcpttos* are the envelope recipients and *data* is a string
75      containing the contents of the e-mail (which should be in :rfc:`5321`
76      format).
77
78      If the *decode_data* constructor keyword is set to ``True``, the *data*
79      argument will be a unicode string.  If it is set to ``False``, it
80      will be a bytes object.
81
82      *kwargs* is a dictionary containing additional information. It is empty
83      if ``decode_data=True`` was given as an init argument, otherwise
84      it contains the following keys:
85
86          *mail_options*:
87             a list of all received parameters to the ``MAIL``
88             command (the elements are uppercase strings; example:
89             ``['BODY=8BITMIME', 'SMTPUTF8']``).
90
91          *rcpt_options*:
92             same as *mail_options* but for the ``RCPT`` command.
93             Currently no ``RCPT TO`` options are supported, so for now
94             this will always be an empty list.
95
96      Implementations of ``process_message`` should use the ``**kwargs``
97      signature to accept arbitrary keyword arguments, since future feature
98      enhancements may add keys to the kwargs dictionary.
99
100      Return ``None`` to request a normal ``250 Ok`` response; otherwise
101      return the desired response string in :RFC:`5321` format.
102
103   .. attribute:: channel_class
104
105      Override this in subclasses to use a custom :class:`SMTPChannel` for
106      managing SMTP clients.
107
108   .. versionadded:: 3.4
109      The *map* constructor argument.
110
111   .. versionchanged:: 3.5
112      *localaddr* and *remoteaddr* may now contain IPv6 addresses.
113
114   .. versionadded:: 3.5
115      The *decode_data* and *enable_SMTPUTF8* constructor parameters, and the
116      *kwargs* parameter to :meth:`process_message` when *decode_data* is
117      ``False``.
118
119   .. versionchanged:: 3.6
120      *decode_data* is now ``False`` by default.
121
122
123DebuggingServer Objects
124-----------------------
125
126
127.. class:: DebuggingServer(localaddr, remoteaddr)
128
129   Create a new debugging server.  Arguments are as per :class:`SMTPServer`.
130   Messages will be discarded, and printed on stdout.
131
132
133PureProxy Objects
134-----------------
135
136
137.. class:: PureProxy(localaddr, remoteaddr)
138
139   Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
140   Everything will be relayed to *remoteaddr*.  Note that running this has a good
141   chance to make you into an open relay, so please be careful.
142
143
144MailmanProxy Objects
145--------------------
146
147
148.. class:: MailmanProxy(localaddr, remoteaddr)
149
150   .. deprecated-removed:: 3.9 3.11
151
152      :class:`MailmanProxy` is deprecated, it depends on a ``Mailman``
153      module which no longer exists and therefore is already broken.
154
155
156   Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
157   Everything will be relayed to *remoteaddr*, unless local mailman configurations
158   knows about an address, in which case it will be handled via mailman.  Note that
159   running this has a good chance to make you into an open relay, so please be
160   careful.
161
162SMTPChannel Objects
163-------------------
164
165.. class:: SMTPChannel(server, conn, addr, data_size_limit=33554432,\
166                       map=None, enable_SMTPUTF8=False, decode_data=False)
167
168   Create a new :class:`SMTPChannel` object which manages the communication
169   between the server and a single SMTP client.
170
171   *conn* and *addr* are as per the instance variables described below.
172
173   *data_size_limit* specifies the maximum number of bytes that will be
174   accepted in a ``DATA`` command.  A value of ``None`` or ``0`` means no
175   limit.
176
177   *enable_SMTPUTF8* determines whether the ``SMTPUTF8`` extension (as defined
178   in :RFC:`6531`) should be enabled.  The default is ``False``.
179   *decode_data* and *enable_SMTPUTF8* cannot be set to ``True`` at the same
180   time.
181
182   A dictionary can be specified in *map* to avoid using a global socket map.
183
184   *decode_data* specifies whether the data portion of the SMTP transaction
185   should be decoded using UTF-8.  The default is ``False``.
186   *decode_data* and *enable_SMTPUTF8* cannot be set to ``True`` at the same
187   time.
188
189   To use a custom SMTPChannel implementation you need to override the
190   :attr:`SMTPServer.channel_class` of your :class:`SMTPServer`.
191
192   .. versionchanged:: 3.5
193      The *decode_data* and *enable_SMTPUTF8* parameters were added.
194
195   .. versionchanged:: 3.6
196      *decode_data* is now ``False`` by default.
197
198   The :class:`SMTPChannel` has the following instance variables:
199
200   .. attribute:: smtp_server
201
202      Holds the :class:`SMTPServer` that spawned this channel.
203
204   .. attribute:: conn
205
206      Holds the socket object connecting to the client.
207
208   .. attribute:: addr
209
210      Holds the address of the client, the second value returned by
211      :func:`socket.accept <socket.socket.accept>`
212
213   .. attribute:: received_lines
214
215      Holds a list of the line strings (decoded using UTF-8) received from
216      the client. The lines have their ``"\r\n"`` line ending translated to
217      ``"\n"``.
218
219   .. attribute:: smtp_state
220
221      Holds the current state of the channel. This will be either
222      :attr:`COMMAND` initially and then :attr:`DATA` after the client sends
223      a "DATA" line.
224
225   .. attribute:: seen_greeting
226
227      Holds a string containing the greeting sent by the client in its "HELO".
228
229   .. attribute:: mailfrom
230
231      Holds a string containing the address identified in the "MAIL FROM:" line
232      from the client.
233
234   .. attribute:: rcpttos
235
236      Holds a list of strings containing the addresses identified in the
237      "RCPT TO:" lines from the client.
238
239   .. attribute:: received_data
240
241      Holds a string containing all of the data sent by the client during the
242      DATA state, up to but not including the terminating ``"\r\n.\r\n"``.
243
244   .. attribute:: fqdn
245
246      Holds the fully-qualified domain name of the server as returned by
247      :func:`socket.getfqdn`.
248
249   .. attribute:: peer
250
251      Holds the name of the client peer as returned by ``conn.getpeername()``
252      where ``conn`` is :attr:`conn`.
253
254   The :class:`SMTPChannel` operates by invoking methods named ``smtp_<command>``
255   upon reception of a command line from the client. Built into the base
256   :class:`SMTPChannel` class are methods for handling the following commands
257   (and responding to them appropriately):
258
259   ======== ===================================================================
260   Command  Action taken
261   ======== ===================================================================
262   HELO     Accepts the greeting from the client and stores it in
263            :attr:`seen_greeting`.  Sets server to base command mode.
264   EHLO     Accepts the greeting from the client and stores it in
265            :attr:`seen_greeting`.  Sets server to extended command mode.
266   NOOP     Takes no action.
267   QUIT     Closes the connection cleanly.
268   MAIL     Accepts the "MAIL FROM:" syntax and stores the supplied address as
269            :attr:`mailfrom`.  In extended command mode, accepts the
270            :rfc:`1870` SIZE attribute and responds appropriately based on the
271            value of *data_size_limit*.
272   RCPT     Accepts the "RCPT TO:" syntax and stores the supplied addresses in
273            the :attr:`rcpttos` list.
274   RSET     Resets the :attr:`mailfrom`, :attr:`rcpttos`, and
275            :attr:`received_data`, but not the greeting.
276   DATA     Sets the internal state to :attr:`DATA` and stores remaining lines
277            from the client in :attr:`received_data` until the terminator
278            ``"\r\n.\r\n"`` is received.
279   HELP     Returns minimal information on command syntax
280   VRFY     Returns code 252 (the server doesn't know if the address is valid)
281   EXPN     Reports that the command is not implemented.
282   ======== ===================================================================
283