Source code for s365b.notify.senders

"""Ways to send email: Microsoft Graph and SMTP."""

from __future__ import annotations

import asyncio
import smtplib
import socket
import ssl
from email.message import EmailMessage
from email.utils import make_msgid
from typing import Protocol

from s365b.graph.client import GraphClient
from s365b.notify.message import Message


[docs] class SendError(Exception): """Sending failed. The message is safe to show."""
[docs] class Notifier(Protocol): """Something that can send an email."""
[docs] name: str
[docs] async def send(self, message: Message, recipients: list[str]) -> None: """Send one message. Args: message: The message. recipients: To addresses. Raises: SendError: If sending failed. """
[docs] class GraphNotifier: """Sends as a mailbox through ``/users/{sender}/sendMail``. The Notifications app may send only as that mailbox: its ``Mail.Send`` is an Exchange RBAC assignment scoped to it, not a tenant-wide grant. Args: graph: Graph client authenticated as the Notifications app. sender: Sender mailbox address. """
[docs] name = "graph"
def __init__(self, graph: GraphClient, sender: str) -> None:
[docs] self.graph = graph
[docs] self.sender = sender
[docs] async def send(self, message: Message, recipients: list[str]) -> None: """Send one message (not saved to Sent Items). Args: message: The message. recipients: To addresses. Raises: SendError: If Graph refuses or cannot be reached. """ from s365b.graph.client import GraphError payload = { "message": { "subject": message.subject, "body": {"contentType": "HTML", "content": message.html}, "toRecipients": [{"emailAddress": {"address": r}} for r in recipients], }, "saveToSentItems": False, } try: await self.graph.request( "POST", f"/users/{self.sender}/sendMail", json=payload, idempotent=False ) except GraphError as exc: hint = "" if exc.status in (401, 403): hint = ( " The Notifications app may send only after the Exchange step" " (scoped Mail.Send) is done; it can take up to two hours to apply." ) elif exc.status == 404: hint = f" Check that the mailbox {self.sender} exists." raise SendError(f"Microsoft Graph: {exc}.{hint}") from exc except Exception as exc: raise SendError(f"Microsoft Graph: {type(exc).__name__}: {exc}") from exc
[docs] class SmtpNotifier: """Sends through an SMTP relay. Args: host: Relay host. port: Port. security: ``starttls``, ``tls`` (implicit) or ``none``. sender: From address. username: Login user; empty for none. password: Login password. timeout: Socket timeout in seconds. """
[docs] name = "smtp"
def __init__( self, host: str, port: int, security: str, sender: str, username: str = "", password: str = "", timeout: float = 30.0, ) -> None: self.host, self.port, self.security = host, port, security self.sender, self.username, self.password = sender, username, password
[docs] self.timeout = timeout
def _build(self, message: Message, recipients: list[str]) -> EmailMessage: msg = EmailMessage() msg["Subject"] = message.subject msg["From"] = self.sender msg["To"] = ", ".join(recipients) msg["Message-ID"] = make_msgid(domain=self.sender.rpartition("@")[2] or None) msg.set_content(message.text) msg.add_alternative(message.html, subtype="html") return msg def _send_sync(self, msg: EmailMessage) -> None: context = ssl.create_default_context() smtp: smtplib.SMTP if self.security == "tls": smtp = smtplib.SMTP_SSL(self.host, self.port, timeout=self.timeout, context=context) else: smtp = smtplib.SMTP(self.host, self.port, timeout=self.timeout) with smtp: if self.security == "starttls": smtp.starttls(context=context) if self.username: smtp.login(self.username, self.password) smtp.send_message(msg)
[docs] async def send(self, message: Message, recipients: list[str]) -> None: """Send one message. Args: message: The message. recipients: To addresses. Raises: SendError: For connection, TLS, authentication or relay errors. """ if not self.host or not self.sender: raise SendError("SMTP is not configured (host and from address are required)") try: await asyncio.to_thread(self._send_sync, self._build(message, recipients)) except smtplib.SMTPAuthenticationError as exc: raise SendError(f"SMTP {self.host}: the username or password was refused") from exc except (OSError, smtplib.SMTPException) as exc: raise SendError(f"SMTP {self.host}:{self.port}: {_explain(exc)}") from exc
def _explain(exc: Exception) -> str: """Turn common socket and TLS errors into a sentence.""" if isinstance(exc, ConnectionRefusedError): return "connection refused (is the server name and port right?)" if isinstance(exc, socket.gaierror): return "the server name could not be found" if isinstance(exc, TimeoutError | socket.timeout): return "no answer from the server (firewall, or wrong port?)" if isinstance(exc, ssl.SSLError): return f"TLS failed ({exc.reason or exc}); check the security setting and port" if isinstance(exc, smtplib.SMTPNotSupportedError): return "the server does not offer STARTTLS; try TLS or a different port" return str(exc)