From 8ad723f4d3632bb8b8f5a3784900690a47126091 Mon Sep 17 00:00:00 2001 From: Olivier Ramonat Date: Fri, 19 Jun 2020 07:42:39 +0200 Subject: [PATCH] Add small send_message helper to quickly send email TN: T518-022 --- src/e3/net/smtp.py | 31 ++++++++++++++++++++++++++++ tests/tests_e3/net/smtp/main_test.py | 26 +++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/src/e3/net/smtp.py b/src/e3/net/smtp.py index 59230ccc..adeb9b28 100644 --- a/src/e3/net/smtp.py +++ b/src/e3/net/smtp.py @@ -2,9 +2,11 @@ import os import smtplib +from email.message import Message import e3.log import e3.os.process +from e3.error import E3Error from typing import TYPE_CHECKING @@ -112,3 +114,32 @@ def system_sendmail() -> bool: logger.debug("Message-ID: %s sent successfully", message_id) return True + + +def send_message( + from_email: str, + to_emails: List[str], + subject: str, + content: str, + smtp_servers: List[str], +) -> None: + """Send an e-mail message. + + :param from_email: the address sending this email (e.g. user@example.com) + :param to_emails: A list of addresses to send this email to + :param subject: the e-mail's subject + :param content: the e-mail's content + """ + msg = Message() + msg["To"] = ", ".join(to_emails) + msg["From"] = from_email + msg["Subject"] = subject + msg.set_payload(content, "utf-8") + + if not sendmail( + from_email=from_email, + to_emails=to_emails, + mail_as_string=msg.as_string(), + smtp_servers=smtp_servers, + ): + raise E3Error(f"error when sending email {subject}") diff --git a/tests/tests_e3/net/smtp/main_test.py b/tests/tests_e3/net/smtp/main_test.py index 84cbe523..a914b7b8 100644 --- a/tests/tests_e3/net/smtp/main_test.py +++ b/tests/tests_e3/net/smtp/main_test.py @@ -2,8 +2,10 @@ from email.utils import make_msgid import e3.net.smtp +from e3.error import E3Error import mock +import pytest def test_sendmail(): @@ -74,3 +76,27 @@ def error_on_quit(): ) assert result is True assert "Message-ID: %s sent successfully" % mid in caplog.text + + +def test_send_message(): + from_addr = "e3@example.net" + to_addresses = ["info@example.net", "info@example.com"] + msg_content = "test mail content" + msg_subject = "test mail subject" + + with mock.patch("smtplib.SMTP_SSL") as mock_smtp: + smtp_mock = mock_smtp.return_value + smtp_mock.sendmail.return_value = {} + e3.net.smtp.send_message( + from_addr, to_addresses, msg_subject, msg_content, ["smtp.localhost"] + ) + + assert smtp_mock.sendmail.called + assert smtp_mock.sendmail.call_count == 1 + + smtp_mock.sendmail.return_value = {"error": 2} + + with pytest.raises(E3Error): + e3.net.smtp.send_message( + from_addr, to_addresses, msg_subject, msg_content, ["smtp.localhost"] + )