Skip to content

Instantly share code, notes, and snippets.

@ultimatecoder
Last active October 12, 2018 14:01
Show Gist options
  • Save ultimatecoder/dac0ea0d0655f45fd2f3da078e5bac28 to your computer and use it in GitHub Desktop.
Save ultimatecoder/dac0ea0d0655f45fd2f3da078e5bac28 to your computer and use it in GitHub Desktop.
A Python script to send emails
#! /usr/bin/python
import argparse
import logging
import os
import smtplib
import sys
def get_receiver_emails(_file):
"""Reads list of emails from a file.
The list of emails are seperated by a new line.
"""
emails = []
with _file as f:
raw_emails = f.read()
emails = raw_emails.split()
return emails
def read_message(_file):
"""Reads email message and returns it."""
message = ""
with _file as f:
message = f.read()
return message
def load_context():
"""Reads environment variable and returns the context."""
context = {
"host": os.environ.get("SMTP_HOST", "localhost"),
"port": os.environ.get("SMTP_PORT", 465),
"username": os.environ.get("SMTP_USERNAME", "test@test.com"),
"password": os.environ.get("SMTP_PASSWORD", "test"),
"from_address": os.environ.get("FROM_EMAIL", "test@test.com"),
}
return context
def start(context):
"""Starts the process of sending mails."""
with smtplib.SMTP_SSL(host=context["host"], port=context["port"]) as server:
try:
logging.debug("Connecting to the SMTP server.")
server.login(context["username"], context["password"])
logging.debug("Connected to the SMTP server.")
except smtplib.SMTPAuthenticationError as e:
sys.exit(2)
for to_address in context["to_addresses"]:
try:
logging.debug(f"From email {context['from_address']}")
logging.debug(f"To email {to_address}")
logging.debug(f"Message {context['message']}")
server.sendmail(
context["from_address"],
to_address,
context["message"]
)
logging.info(f"Mail sent to {to_address}")
except smtplib.SMTPSenderRefused as e:
logging.error("Error: Connection refused by the SMTP server.")
sys.exit(2)
except smtplib.SMTPDataError as e:
logging.error("Error: Invalid email body received.")
sys.exit(2)
def init_logger(log_level):
"""Initialize logger."""
level = getattr(logging, log_level.upper())
logging.basicConfig(level=level)
if __name__ == "__main__":
description = "A script to send individual mails to the receptions."
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
'addresses',
type=open,
help='File containing list of email addresses separated by new-line.'
)
parser.add_argument(
'message',
type=open,
help='File containing email body in plain text.'
)
parser.add_argument(
'--log-level',
'-l',
type=str,
default="info",
choices=["debug", "info", "warning", "error", "critical"]
)
args = parser.parse_args()
init_logger(args.log_level)
context = load_context()
context["to_addresses"] = get_receiver_emails(args.addresses),
context["message"] = read_message(args.message)
start(context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment