Source code for fmn.sender.email

# SPDX-FileCopyrightText: Contributors to the Fedora Project
#
# SPDX-License-Identifier: MIT

import logging
import socket
from email.message import EmailMessage
from email.utils import localtime

from aiosmtplib import SMTP, SMTPServerDisconnected

from .handler import Handler

log = logging.getLogger(__name__)


[docs] class EmailHandler(Handler):
[docs] async def setup(self): self._smtp = SMTP( hostname=self._config.get("smtp_host", "localhost"), port=self._config.get("smtp_port", 25), ) await self._smtp.connect()
[docs] async def stop(self): await self._smtp.quit()
[docs] async def handle(self, message): # Test with `python -m smtpd -c DebuggingServer -n` notif = EmailMessage() notif["From"] = self._config["from"] notif.add_header( "Received", f"from fedora-messaging by FMN ({socket.getfqdn()}) ; {localtime()}" ) for name, value in message["headers"].items(): notif[name] = value body = message["body"] if message.get("footer") is not None: body = f"{body}\n\n-- \n{message['footer']}" notif.set_content(body) log.info("Sending email to %s with subject %s", notif["To"], notif["Subject"]) try: await self._smtp.send_message(notif) except SMTPServerDisconnected: # Reconnect log.debug("Reconnecting to the SMTP server") self._smtp.close() await self._smtp.connect() await self._smtp.send_message(notif) log.debug("The email was sent")