Skip to content

Commit

Permalink
Merge pull request #396 from enzbang/send-message-helper
Browse files Browse the repository at this point in the history
Add small send_message helper to quickly send email
  • Loading branch information
camilo1729 authored Jun 22, 2020
2 parents 01f1873 + 8ad723f commit 89a089b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/e3/net/smtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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. [email protected])
: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}")
26 changes: 26 additions & 0 deletions tests/tests_e3/net/smtp/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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 = "[email protected]"
to_addresses = ["[email protected]", "[email protected]"]
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"]
)

0 comments on commit 89a089b

Please sign in to comment.