Created
July 8, 2021 20:25
-
-
Save stevekm/213bad2275bdbb9387e9cc80184ce4f9 to your computer and use it in GitHub Desktop.
Python helper module for writing and sending emails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Module to send email messages | |
https://www.tutorialspoint.com/python/python_sending_email.htm | |
""" | |
import getpass | |
import smtplib | |
# default global configs | |
username = getpass.getuser() | |
domain = 'server.com' | |
SMTP_server = 'localhost' | |
sender = { | |
'name': "Sender Name Here", | |
'address': username + '@' + domain | |
} | |
receivers = [ | |
{ | |
'name': "Reciever Name Here", | |
'address': username + '@' + domain | |
} | |
] | |
# NOTE: must start with 'Subject:' | |
subject = 'Subject: Subject line goes here' | |
message_body = """ | |
Message body goes here | |
""" | |
def create_header_line(user_data, to_or_from = "From"): | |
""" | |
Make the email header lines that look like this: | |
From: From Person <[email protected]> | |
To: To Person <[email protected]> | |
""" | |
header_string = "{to_or_from}: {user_name} <{user_email}>".format( | |
to_or_from = to_or_from, | |
user_name = user_data['name'], | |
user_email = user_data['address'] | |
) | |
return(header_string) | |
def create_message(sender = sender, receivers = receivers, subject = subject, message_body = message_body): | |
""" | |
Make the email message contents | |
""" | |
from_line = create_header_line(user_data = sender, to_or_from = "From") | |
to_line = create_header_line(user_data = receivers[0], to_or_from = "To") # TODO: need to deal with a list of email addresses here | |
subject_line = subject # TODO: required to start with 'Subject: '; need to just prepend that here | |
message_str = """{from_line} | |
{to_line} | |
{subject_line} | |
{message_body} | |
""".format( | |
from_line = from_line, | |
to_line = to_line, | |
subject_line = subject_line, | |
message_body = message_body | |
) | |
return(message_str) | |
def send_email(sender, receivers_list, message): | |
""" | |
Send the email | |
""" | |
try: | |
smtpObj = smtplib.SMTP(SMTP_server) | |
smtpObj.sendmail(sender, receivers_list, message) | |
except: # SMTPException | |
raise | |
if __name__ == '__main__': | |
try: | |
send_email( | |
sender = sender['address'], | |
receivers_list = [ r['address'] for r in receivers ], | |
message = create_message()) | |
print("Successfully sent email:") | |
print(create_message()) | |
except: | |
print("Error: unable to send email") | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment