At the heart of this module is the
SMTP
类在
aiosmtpd.smtp
module. This class implements the
RFC 5321
Simple Mail Transport Protocol. Often you won’t run an
SMTP
instance directly, but instead will use a
Controller
instance to run the server in a subthread.
>>> from aiosmtpd.controller import Controller
SMTP
class is itself a subclass of
StreamReaderProtocol
While behavior for common SMTP commands can be specified using
handlers
, more complex specializations such as adding custom SMTP commands require subclassing the
SMTP
类。
For example, let’s say you wanted to add a new SMTP command called
PING
. All methods implementing
SMTP
commands are prefixed with
smtp_
; they must also be coroutines. Here’s how you could implement this use case:
>>> import asyncio >>> from aiosmtpd.smtp import SMTP as Server, syntax >>> class MyServer(Server): ... @syntax('PING [ignored]') ... async def smtp_PING(self, arg): ... await self.push('259 Pong')
Now let’s run this server in a controller:
>>> from aiosmtpd.handlers import Sink >>> class MyController(Controller): ... def factory(self): ... return MyServer(self.handler) >>> controller = MyController(Sink()) >>> controller.start()
We can now connect to this server with an
SMTP
client.
>>> from smtplib import SMTP as Client >>> client = Client(controller.hostname, controller.port)
Let’s ping the server. Since the
PING
command isn’t an official
SMTP
command, we have to use the lower level interface to talk to it.
>>> code, message = client.docmd('PING') >>> code 259 >>> message b'Pong'
Because we prefixed the
smtp_PING()
method with the
@syntax()
decorator, the command shows up in the
HELP
output.
>>> print(client.help().decode('utf-8')) Supported commands: AUTH DATA EHLO HELO HELP MAIL NOOP PING QUIT RCPT RSET VRFY
And we can get more detailed help on the new command.
>>> print(client.help('PING').decode('utf-8')) Syntax: PING [ignored]
Don’t forget to
stop()
the controller when you’re done.
>>> controller.stop()
警告
These methods are deprecated. See handler hooks 代替。
SMTP
server class also implements some hooks which your subclass can override to provide additional responses.
ehlo_hook()
This hook makes it possible for subclasses to return additional
EHLO
responses. This method, called
asynchronously
and taking no arguments, can do whatever it wants, including (most commonly) pushing new
250-<command>
responses to the client. This hook is called just before the standard
250 HELP
which ends the
EHLO
响应来自服务器。
rset_hook()
This hook makes it possible to return additional
RSET
responses. This method, called
asynchronously
and taking no arguments, is called just before the standard
250 OK
which ends the
RSET
响应来自服务器。
aiosmtpd.smtp.
AuthenticatorType
= Callable[[SMTP, Session, Envelope, str, Any], AuthResult]
¶
@
aiosmtpd.smtp.
auth_mechanism
(
actual_name
)
¶
actual_name ( str ) – Name of the AUTH Mechanism implemented by the method. See AUTH Mechanism Hooks for more info.
This decorator specifies the actual name of the AUTH Mechanism implemented by the method being decorated, regardless of the method’s name.
重要
The decorated method’s name MUST still start with
auth_
aiosmtpd.smtp.
AuthResult
¶
Contains the result of the Authentication Procedure.
For more info, please see
AuthResult
aiosmtpd.smtp.
LoginPassword
(
login
:
bytes
,
password
:
bytes
)
¶
子类化的
typing.NamedTuple
that holds the Authentication Data for the built-in
LOGIN
and
PLAIN
AUTH Mechanisms.
It is to be used for Authentication purposes by
Authenticator()
For more information, please refer to the 身份验证系统 页面。
aiosmtpd.smtp.
SMTP
(
handler
,
*
,
data_size_limit
=
33554432
,
enable_SMTPUTF8
=
False
,
decode_data
=
False
,
hostname
=
None
,
ident
=
None
,
tls_context
=
None
,
require_starttls
=
False
,
timeout
=
300
,
auth_required
=
False
,
auth_require_tls
=
True
,
auth_exclude_mechanism
=
None
,
auth_callback
=
None
,
authenticator
=
None
,
command_call_limit
=
None
,
proxy_protocol_timeout
=
None
,
loop
=
None
)
¶
handler
¶
An instance of a handler class that optionally can implement 处理程序挂钩 .
data_size_limit
:
int
= 33554432
The limit in number of bytes that is accepted for client SMTP commands. It is returned to ESMTP clients in the
250-SIZE
响应。
enable_SMTPUTF8
:
bool
= False
当
True
, causes the ESMTP
SMTPUTF8
option to be returned to the client, and allows for UTF-8 content to be accepted, as defined in
RFC 6531
.
decode_data
:
bool
= False
¶
当
True
, attempts to decode byte content in the
DATA
command, assigning the string value to the
envelope’s
content
属性。
hostname
: Optional
[
str
]
= None
The first part of the string returned in the
220
greeting response given to clients when they first connect to the server. If not given, the system’s fully-qualified domain name is used.
ident
: Optional
[
str
]
= None
¶
The second part of the string returned in the
220
greeting response that identifies the software name and version of the SMTP server to the client. If not given, a default Python SMTP ident is used.
tls_context
: Optional
[
ssl.SSLContext
]
= None
实例化的
ssl.SSLContext
. Providing this will enable support for
STARTTLS
ESMTP/LMTP option as defined in
RFC 3207
.
见
启用 STARTTLS
for a more in-depth discussion on enabling
STARTTLS
.
require_starttls
:
bool
= False
若设为
True
, then client must send
STARTTLS
before “restricted” ESMTP commands can be issued.
“Restricted” ESMTP commands are all commands not in the set
{"NOOP", "EHLO", "STARTTLS", "QUIT"}
timeout
: Union
[
int
,
float
]
= 300
¶
The number of seconds to wait between valid SMTP commands. After this time the connection will be closed by the server.
The default is 300 seconds, as per RFC 2821 .
auth_required
:
bool
= False
¶
Specifies whether SMTP Authentication is mandatory or not for the session. This impacts some SMTP commands such as
HELP
,
MAIL FROM
,
RCPT TO
,等。
auth_require_tls
:
bool
= True
¶
指定是否
STARTTLS
must be used before AUTH exchange or not.
If you set this to
False
then AUTH exchange can be done outside a TLS context, but the class will warn you of security considerations.
不起作用若
require_starttls
is
True
.
auth_exclude_mechanism
: Optional
[
Iterable
[
str
]
]
= None
¶
Specifies which AUTH mechanisms to NOT use.
This is the only way to completely disable the built-in AUTH mechanisms.
见 身份验证系统 for a more in-depth discussion on AUTH mechanisms.
New in version 1.2.2.
auth_callback
: Callable
[
[
str
,
bytes
,
bytes
]
,
bool
]
= login_always_fail
¶
A function that accepts three arguments:
mechanism: str
,
login: bytes
,和
password: bytes
. Based on these args, the function must return a
bool
that indicates whether the client’s authentication attempt is accepted/successful or not.
Deprecated since version 1.3:
使用
authenticator
instead. This parameter
will be removed in version 2.0
.
authenticator
:
aiosmtpd.smtp.AuthenticatorType
= None
¶
A function whose signature is identical to
aiosmtpd.smtp.AuthenticatorType
.
见
Authenticator()
了解更多信息。
New in version 1.3.
command_call_limit
: Optional
[
Union
[
int
,
Dict
[
str
,
int
]
]
]
= None
¶
若非
None
sets the maximum time a certain SMTP command can be invoked. This is to prevent DoS due to malicious client connecting and never disconnecting, due to continual sending of SMTP commands to prevent timeout.
The handling differs based on the type:
若
command_call_limit是类型int, then the value is the call limit for ALL SMTP commands.若
command_call_limit是类型dict,它必须是Dict[str, int](the type of the values will be enforced). The keys will be the SMTP Command to set the limit for, the values will be the call limit per SMTP Command.A special key of
"*"is used to set the ‘default’ call limit for commands not explicitly declared incommand_call_limit。若"*"is not given, then the ‘default’ call limit will be set toaiosmtpd.smtp.CALL_LIMIT_DEFAULTOther types – or a
Dictwhose any value is not anint– will raise aTypeError异常。范例:
# All commands have a limit of 10 calls SMTP(..., command_call_limit=10) # Commands RCPT and NOOP have their own limits; others have an implicit limit # of 20 (CALL_LIMIT_DEFAULT) SMTP(..., command_call_limit={"RCPT": 30, "NOOP": 5}) # Commands RCPT and NOOP have their own limits; others set to 3 SMTP(..., command_call_limit={"RCPT": 20, "NOOP": 10, "*": 3})If not given (or set to
None), then command call limit will not be enforced. This will change in version 2.0 .New in version 1.2.3.
proxy_protocol_timeout
: Optional
[
Union
[
int
,
float
]
]
= None
¶
If given (not
None
), activates support for
PROXY Protocol
.
Please read the PROXY Protocol Support documentation for a more in-depth explanation.
If not given (or
None
), disables support for PROXY Protocol.
警告
When PROXY protocol support is activated,
SMTP
’s behavior changes: It no longer immediately sends
220
greeting upon client connection, but instead it will wait for client to first send the PROXY protocol header.
This is in accordance to the PROXY Protocol standard.
New in version 1.4.
loop
The asyncio event loop to use. If not given,
asyncio.new_event_loop()
will be called to create the event loop.
line_length_limit
¶
The maximum line length, in octets (not characters; one UTF-8 character may result in more than one octet). Defaults to
1001
in compliance with
RFC 5321 § 4.5.3.1.6
Attention
This sets the
stream limit
of
asyncio.StreamReader.readuntil()
, thus impacting how the method works. In previous versions of aiosmtpd, the limit is not set. To return to the behavior of the previous versions, set
line_length_limit
to
2**16
before
instantiating the
SMTP
类。
local_part_limit
¶
The maximum lengh (in octets) of the local part of email addresses.
RFC 5321 § 4.5.3.1.1 specifies a maximum length of 64 octets, but this requirement is flexible and can be relaxed at the server’s discretion (see § 4.5.3.1 ).
Setting this to 0 (the default) disables this limit completely.
AuthLoginUsernameChallenge
¶
str
containing the base64-encoded challenge to be sent as the first challenge in the
AUTH LOGIN
机制。
AuthLoginPasswordChallenge
¶
str
containing the base64-encoded challenge to be sent as the second challenge in the
AUTH LOGIN
机制。
event_handler
¶
handler instance passed into the constructor.
data_size_limit
¶
值对于 data_size_limit argument passed into the constructor.
enable_SMTPUTF8
¶
值对于 enable_SMTPUTF8 argument passed into the constructor.
hostname
¶
220
greeting hostname. This will either be the value of the
hostname
argument passed into the constructor, or the system’s fully qualified host name.
tls_context
¶
值对于 tls_context argument passed into the constructor.
require_starttls
¶
True if both the tls_context argument to the constructor was given and require_starttls flag was True.
transport
¶
The active asyncio transport if there is one, otherwise None.
loop
¶
The event loop being used. This will either be the given loop argument, or the new event loop that was created.
authenticated
¶
A flag that indicates whether authentication had succeeded.
_create_session
(
)
¶
A method subclasses can override to return custom
Session
实例。
_create_envelope
(
)
¶
A method subclasses can override to return custom
Envelope
实例。
push
(
status
)
¶
The method that subclasses and handlers should use to return statuses to SMTP clients. This is a coroutine. status can be a bytes object, but for convenience it is more likely to be a string. If it’s a string, it must be ASCII, unless enable_SMTPUTF8 is True in which case it will be encoded as UTF-8.
smtp_<COMMAND>(arg)
Coroutine methods implementing the SMTP protocol commands. For example,
smtp_HELO()
implements the SMTP
HELO
command. Subclasses can override these, or add new command methods to implement custom extensions to the SMTP protocol.
arg
is the rest of the SMTP command given by the client, or None if nothing but the command was given.
challenge_auth
(
challenge
,
encode_to_b64
=
True
,
log_client_response
=
False
)
→ Union
[
_Missing
,
bytes
]
¶
challenge ( Union [ str , bytes , bytearray ] ) – The SMTP AUTH challenge to send to the client. May be in plaintext, may be in base64. Do NOT prefix with “334 “!
encode_to_b64 ( bool ) – If true, will perform base64-encoding before sending the challenge to the client.
log_client_response ( bool ) – If true, will perform logging of client response
Response from client (already base64-decoded) or
MISSING
(see description)
This method will return
MISSING
if either of these scenarios happen:
client aborted the
AUTH
procedure by sending
b"*"
,或
client response to the challenge cannot be base64-decoded.
警告
设置
log_client_response=True
might cause leakage of sensitive information!
DO NOT TURN ON UNLESS ABSOLUTELY NECESSARY!
To enable
RFC 3207
STARTTLS
, you must supply the
tls_context
自变量到
SMTP
类。
tls_context
is created with the
ssl.create_default_context()
call from the
ssl
module, as follows:
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
The context must be initialized with a server certificate, private key, and/or intermediate CA certificate chain with the
ssl.SSLContext.load_cert_chain()
method. This can be done with separate files, or an all in one file. Files must be in PEM format.
For example, if you wanted to use a self-signed certification for localhost, which is easy to create but doesn’t provide much security, you could use the openssl(1) command like so:
$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \ -days 365 -nodes -subj '/CN=localhost'
and then in Python:
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain('cert.pem', 'key.pem')
现在传递
context
对象到
tls_context
argument in the
SMTP
构造函数。
Note that a number of exceptions can be generated by these methods, and by SSL connections, which you must be prepared to handle. Additional documentation is available in Python’s
ssl
module, and should be reviewed before use; in particular if client authentication and/or advanced error handling is desired.
若
require_starttls
is
True
, a TLS session must be initiated for the server to respond to any commands other than
EHLO
/
LHLO
,
NOOP
,
QUIT
,和
STARTTLS
.
若
require_starttls
is
False
(the default), use of TLS is not required; the client
may
upgrade the connection to TLS, or may use any supported command over an insecure connection.
若
tls_context
is not supplied, the
STARTTLS
option will not be advertised, and the
STARTTLS
command will not be accepted.
require_starttls
is meaningless in this case, and should be set to
False
.