43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import smtplib
|
|
from email.message import EmailMessage
|
|
|
|
|
|
class EmailNotifier:
|
|
def __init__(
|
|
self,
|
|
*,
|
|
host: str | None,
|
|
port: int,
|
|
username: str | None,
|
|
password: str | None,
|
|
from_address: str | None,
|
|
use_tls: bool,
|
|
) -> None:
|
|
self.host = host
|
|
self.port = port
|
|
self.username = username
|
|
self.password = password
|
|
self.from_address = from_address
|
|
self.use_tls = use_tls
|
|
|
|
@property
|
|
def configured(self) -> bool:
|
|
return bool(self.host and self.from_address)
|
|
|
|
def send(self, *, to_address: str, subject: str, body: str) -> None:
|
|
if not self.configured:
|
|
return
|
|
message = EmailMessage()
|
|
message["Subject"] = subject
|
|
message["From"] = self.from_address
|
|
message["To"] = to_address
|
|
message.set_content(body)
|
|
with smtplib.SMTP(self.host, self.port, timeout=10) as smtp:
|
|
if self.use_tls:
|
|
smtp.starttls()
|
|
if self.username and self.password:
|
|
smtp.login(self.username, self.password)
|
|
smtp.send_message(message)
|