SMTPAdapter
What it is
- An
IEmailAdapterimplementation that sends emails via SMTP using Python’ssmtplib. - Supports plain text and optional HTML alternative bodies.
- Supports optional authentication and optional TLS or SSL.
Public API
class SMTPAdapter(IEmailAdapter)__init__(*, host: str, port: int, username: str | None = None, password: str | None = None, use_tls: bool = False, use_ssl: bool = False, timeout: int = 10) -> None- Configures SMTP connection parameters.
- Validates that
use_tlsanduse_sslare not both enabled.
send(*, to_email: str, subject: str, text_body: str, html_body: str | None = None, from_email: str, from_name: str | None = None, reply_to: str | None = None) -> None- Builds an
EmailMessagewith:To,Subject,From(formatted withfrom_namewhen provided), optionalReply-To- plain text body, and optional HTML alternative
- Connects using SMTP or SMTP-over-SSL, optionally upgrades to TLS, optionally logs in, then sends.
- Builds an
Configuration/Dependencies
- Standard library:
smtplib(SMTP,SMTP_SSL)email.message.EmailMessageemail.utils.formataddr
- Project dependency:
- Implements
naas_abi_core.services.email.EmailPorts.IEmailAdapter
- Implements
- Parameters:
host,port: SMTP server address.use_ssl: usessmtplib.SMTP_SSLwhenTrue.use_tls: callsstarttls()whenTrue(only when not using SSL).username/password: if both provided,login()is performed.timeout: passed to the SMTP client constructor.
Usage
from naas_abi_core.services.email.adapters.secondary.SMTPAdapter import SMTPAdapter
adapter = SMTPAdapter(
host="smtp.example.com",
port=587,
username="user",
password="pass",
use_tls=True,
timeout=10,
)
adapter.send(
to_email="[email protected]",
subject="Hello",
text_body="Plain text body",
html_body="<p>HTML body</p>",
from_email="[email protected]",
from_name="Sender Name",
reply_to="[email protected]",
)
Caveats
use_tlsanduse_sslcannot both beTrue(raisesValueError).- Authentication occurs only if both
usernameandpasswordare provided. - No attachments, CC/BCC, or custom headers are handled in this adapter.