Creating an Email Decorator with Python and AWS
See Python: Tips and Tricks for similar articles.
The Python code below shows how to create a decorator that will email the output of the decorated function to some email address:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# AWS Configuration
host = "email-smtp.us-east-1.amazonaws.com" # your host may be different
username = "your-aws-smtp-username"
pw = "your-aws-smtp-password"
port = 587
def email(f):
def f2(subject):
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = "foo@example.com"
msg["To"] = "bar@example.com"
text = f()
mime_text = MIMEText(text, "plain")
msg.attach(mime_text)
s = smtplib.SMTP(host, port)
s.starttls()
s.login(username, pw)
s.send_message(msg)
s.quit()
return f2
@email
def foo():
return "Hello, world!"
foo("My Report")SMTP Service
You can use any SMTP service you like for this. If you use AWS, you will have to create and get your SMTP credentials. I got mine at https://console.aws.amazon.com/ses/home?region=us-east-1#smtp-settings:
