API Reference

Protocol

class smtpproto.protocol.ClientState(value)

Bases: enum.Enum

Enumerates all possible protocol states.

greeting_expected = 1

expecting a greeting from the server

greeting_received = 2

received a greeting from the server, ready to authenticate

authenticating = 3

authentication in progress

authenticated = 4

authentication done

ready = 5

ready to send commands

mailtx = 6

in a mail transaction

recipient_sent = 7

sent at least one recipient

send_data = 8

ready to send the message data

data_sent = 9

message data sent

finished = 10

session finished

exception smtpproto.protocol.SMTPException

Bases: Exception

Base class for SMTP exceptions.

exception smtpproto.protocol.SMTPMissingExtension

Bases: smtpproto.protocol.SMTPException

Raised when a required SMTP extension is not present on the server.

exception smtpproto.protocol.SMTPUnsupportedAuthMechanism

Bases: smtpproto.protocol.SMTPException

Raised when trying to authenticate using a mechanism not supported by the server.

exception smtpproto.protocol.SMTPProtocolViolation

Bases: smtpproto.protocol.SMTPException

Raised when there has been a violation of the (E)SMTP protocol by either side.

class smtpproto.protocol.SMTPResponse(code, message)

Bases: object

Represents a response from the server.

code: int

response status code (between 100 and 599)

message: str

response message

is_error()

Return True if this is an error response, False if not.

Return type

bool

raise_as_exception()

Raise an SMTPException from this response.

Return type

NoReturn

class smtpproto.protocol.SMTPClientProtocol

Bases: object

The (E)SMTP protocol state machine.

property state

The current state of the protocol.

Return type

ClientState

property needs_incoming_data

True if the state machine requires more data, False if not.

Return type

bool

get_outgoing_data()

Retrieve any bytes to be sent to the server.

Return type

bytes

property max_message_size

The maximum size of the email message (in bytes) accepted by the server.

Return type

Optional[int]

property auth_mechanisms

The set of authentication mechanisms supported on the server.

Return type

FrozenSet[str]

property extensions

The set of extensions advertised by the server.

Return type

FrozenSet[str]

authenticate(mechanism, secret=None)

Authenticate to the server using the given mechanism and an accompanying secret.

Parameters
  • mechanism (str) – the authentication mechanism (e.g. PLAIN or GSSAPI)

  • secret (Optional[str]) – an optional string (usually containing the credentials) that is added as an argument to the AUTH XXX command

Return type

None

send_authentication_data(data)

Send authentication data to the server.

This method can be called when the server responds with a 334 to an AUTH command.

Parameters

data (str) – authentication data (ASCII compatible; usually base64 encoded)

Return type

None

send_greeting(domain)

Send the initial greeting (EHLO or HELO).

Parameters

domain (str) – the required domain name that represents the client side

Return type

None

noop()

Send the NOOP command (No Operation).

Return type

None

quit()

Send the QUIT command (required to cleanly shut down the session).

Return type

None

mail(sender, *, smtputf8=True)

Send the MAIL FROM command (starts a mail transaction).

Parameters
  • sender (Union[str, Address]) – the sender’s email address

  • smtputf8 (bool) – send the SMTPUTF8 option, if available on the server

Return type

None

recipient(recipient)

Send the RCPT TO command (declare an intended recipient).

Requires an active mail transaction.

Parameters

recipient (Union[str, Address]) – the recipient’s email address

Return type

None

start_data()

Send the DATA command (prepare for sending the email payload).

Requires an active mail transaction, and that at least one recipient has been declared.

Return type

None

data(message)

Send the actual email payload.

Requires that the DATA command has been sent first.

Parameters

message (EmailMessage) – the email message

Return type

None

reset()

Send the RSET command (cancel the active mail transaction).

Return type

None

start_tls()

Send the STARTTLS command (signal the server to initiate a TLS handshake).

Return type

None

feed_bytes(data)

Feed received bytes from the transport into the state machine.

if this method raises SMTPProtocolViolation, the state machine is transitioned to the finished state, and the connection should be closed.

Parameters

data (bytes) – received bytes

Return type

Optional[SMTPResponse]

Returns

a response object if a complete response was received, None otherwise

Raises

SMTPProtocolViolation – if the server sent an invalid response

Authentication

class smtpproto.auth.LoginAuthenticator(username, password)

Bases: smtpproto.auth.SMTPAuthenticator

Authenticates against the server with a username/password combination using the LOGIN method.

Parameters
  • username (str) – user name to authenticate as

  • password (str) – password to authenticate with

authenticate()

Performs authentication against the SMTP server.

This method must return an async generator. Any non-empty values the generator yields are sent to the server as authentication data. The response messages from any 334 responses are sent to the generator.

Return type

AsyncGenerator[str, str]

property mechanism

The name of the authentication mechanism (e.g. PLAIN or GSSAPI).

Return type

str

class smtpproto.auth.OAuth2Authenticator(username)

Bases: smtpproto.auth.SMTPAuthenticator

Authenticates against the server using OAUTH2.

In order to use this authenticator, you must subclass it and implement the get_token() method.

Parameters

username (str) – the user name to authenticate as

authenticate()

Performs authentication against the SMTP server.

This method must return an async generator. Any non-empty values the generator yields are sent to the server as authentication data. The response messages from any 334 responses are sent to the generator.

Return type

AsyncGenerator[str, str]

abstract async get_token()

Obtain a new access token.

Implementors should cache the token and its expiration time and only obtain a new one if the old one has expired or is about to.

Return type

str

Returns

the access token

property mechanism

The name of the authentication mechanism (e.g. PLAIN or GSSAPI).

Return type

str

class smtpproto.auth.PlainAuthenticator(username, password, authorization_id='')

Bases: smtpproto.auth.SMTPAuthenticator

Authenticates against the server with a username/password combination using the PLAIN method.

Parameters
  • username (str) – user name to authenticate as

  • password (str) – password to authenticate with

  • authorization_id (str) – optional authorization ID

authenticate()

Performs authentication against the SMTP server.

This method must return an async generator. Any non-empty values the generator yields are sent to the server as authentication data. The response messages from any 334 responses are sent to the generator.

Return type

AsyncGenerator[str, str]

property mechanism

The name of the authentication mechanism (e.g. PLAIN or GSSAPI).

Return type

str

class smtpproto.auth.SMTPAuthenticator

Bases: object

Interface for providing credentials for authenticating against SMTP servers.

abstract authenticate()

Performs authentication against the SMTP server.

This method must return an async generator. Any non-empty values the generator yields are sent to the server as authentication data. The response messages from any 334 responses are sent to the generator.

Return type

AsyncGenerator[str, str]

abstract property mechanism

The name of the authentication mechanism (e.g. PLAIN or GSSAPI).

Return type

str

Concrete client implementation

class smtpproto.client.AsyncSMTPClient(host, port=587, connect_timeout=30, timeout=60, domain=<factory>, ssl_context=None, authenticator=None)

Bases: anyio.abc.AsyncResource

An asynchronous SMTP client.

This runs on asyncio or any other backend supported by AnyIO.

It is recommended that this client is used as an async context manager instead of manually calling connect() and aclose(), if possible.

Parameters
  • host (str) – host name or IP address of the SMTP server

  • port (int) – port on the SMTP server to connect to

  • connect_timeout (float) – connection timeout (in seconds)

  • timeout (float) – timeout for sending requests and reading responses (in seconds)

  • domain (str) – domain name to send to the server as part of the greeting message

  • ssl_context (Optional[SSLContext]) – SSL context to use for establishing TLS encrypted sessions

  • authenticator (Optional[SMTPAuthenticator]) – authenticator to use for authenticating with the SMTP server

async aclose()

Close the connection, if connected.

Return type

None

async connect()

Connect to the SMTP server.

Return type

None

class smtpproto.client.SyncSMTPClient(*args, async_backend='asyncio', async_backend_options=None, **kwargs)

Bases: object

A synchronous (blocking) SMTP client.

It is recommended that this client is used as a context manager instead of manually calling connect() and close(), if possible.

Parameters
  • host – host name or IP address of the SMTP server

  • port – port on the SMTP server to connect to

  • connect_timeout – connection timeout (in seconds)

  • timeout – timeout for sending requests and reading responses (in seconds)

  • domain – domain name to send to the server as part of the greeting message

  • ssl_context – SSL context to use for establishing TLS encrypted sessions

  • authenticator – authenticator to use for authenticating with the SMTP server

  • async_backend (str) – name of the AnyIO-supported asynchronous backend

  • async_backend_options (Optional[Dict[str, Any]]) – dictionary of keyword arguments passed to anyio.start_blocking_portal()

close()

Close the connection, if connected.

Return type

None

connect()

Connect to the SMTP server.

Return type

None