44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
"""Outgoing mail for 2FA codes, using the Mail* settings in patchbay.conf."""
|
|
|
|
import smtplib
|
|
import ssl
|
|
import sys
|
|
from email.message import EmailMessage
|
|
|
|
|
|
class MailError(Exception):
|
|
pass
|
|
|
|
|
|
def send(conf, to, subject, body):
|
|
host = conf.get("mailhost")
|
|
if not host:
|
|
raise MailError("mail server is not configured")
|
|
if host == "log":
|
|
# Development only: MailHost = log prints mails to the server log.
|
|
print(f"[mail to {to}] {subject}\n{body}", file=sys.stderr, flush=True)
|
|
return
|
|
|
|
msg = EmailMessage()
|
|
msg["From"] = conf.get("mailfrom") or conf.get("mailuser")
|
|
msg["To"] = to
|
|
msg["Subject"] = subject
|
|
msg.set_content(body)
|
|
|
|
port = conf.getint("mailport", 587)
|
|
security = (conf.get("mailsecurity") or "starttls").lower()
|
|
ctx = ssl.create_default_context()
|
|
try:
|
|
if security == "ssl":
|
|
server = smtplib.SMTP_SSL(host, port, context=ctx, timeout=20)
|
|
else:
|
|
server = smtplib.SMTP(host, port, timeout=20)
|
|
with server:
|
|
if security == "starttls":
|
|
server.starttls(context=ctx)
|
|
if conf.get("mailuser"):
|
|
server.login(conf.get("mailuser"), conf.get("mailpassword"))
|
|
server.send_message(msg)
|
|
except (OSError, smtplib.SMTPException) as e:
|
|
raise MailError(str(e)) from e
|