aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2024-05-29 12:02:25 -0500
committerFrederick Muriuki Muriithi2024-06-03 10:02:06 -0500
commit4c928dcb959a68510bada756f48d5edc7409bff5 (patch)
tree2db5fca668ba45dfbedbeba5dacad3793b264aae
parentc19058f63b8f4d8644de49be0fd7a1b63ff24ae4 (diff)
downloadgn-auth-4c928dcb959a68510bada756f48d5edc7409bff5.tar.gz
Set module for sending emails.
-rw-r--r--gn_auth/smtp.py56
1 files changed, 56 insertions, 0 deletions
diff --git a/gn_auth/smtp.py b/gn_auth/smtp.py
new file mode 100644
index 0000000..42d8eae
--- /dev/null
+++ b/gn_auth/smtp.py
@@ -0,0 +1,56 @@
+"""Handle sending emails. Uses Python3's `smtplib`."""
+import smtplib
+import mimetypes
+from typing import Optional
+from email.message import EmailMessage
+from email.headerregistry import Address
+
+
+def __read_mime__(filepath) -> dict:
+ """Read mimetype for attachments"""
+ _mime,_extras = mimetypes.guess_type(filepath)
+ if bool(_mime):
+ return dict(zip(("maintype", "subtype"),
+ _mime.split("/")))# type: ignore[union-attr]
+ return {}
+
+
+def build_email_message(# pylint: disable=[too-many-arguments]
+ to_addresses: tuple[Address, ...],
+ subject: str,
+ txtmessage: str,
+ htmlmessage: str = "",
+ attachments: tuple[str, ...] = tuple(),
+ from_address: Address = Address(
+ "GeneNetwork Automated Emails", "no-reply", "genenetwork.org")
+) -> EmailMessage:
+ """Build an email message."""
+ msg = EmailMessage()
+ msg["From"] = from_address
+ msg["To"] = to_addresses
+ msg["Subject"] = subject
+ msg.set_content(txtmessage)
+ if bool(htmlmessage):
+ msg.add_alternative(htmlmessage, subtype="html")
+ for _path in attachments:
+ with open(_path, "rb") as _file:
+ msg.add_attachment(_file.read(), **__read_mime__(_path))
+
+ return msg
+
+
+def send_message(# pylint: disable=[too-many-arguments]
+ smtp_user: str,
+ smtp_passwd: str,
+ message: EmailMessage,
+ host: str = "",
+ port: int = 587,
+ local_hostname: Optional[str]=None,
+ timeout: int = 200,
+ source_address: Optional[tuple[tuple[str, int], ...]] = None
+):
+ """Set up a connection to a SMTP server and send a message."""
+ with smtplib.SMTP(host, port, local_hostname, timeout, source_address) as conn:
+ conn.starttls()
+ conn.login(smtp_user, smtp_passwd)
+ conn.send_message(message)