-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathemail_utils.py
89 lines (68 loc) · 2.5 KB
/
email_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import smtplib
import keyring
from email.message import EmailMessage
from email.headerregistry import Address
from jinja2 import Template
from datetime import datetime
def render_template(path, **kwargs):
'''Renders a Template (Shortcut for a common templating workflow)
Arguments
---------
path: str
Path to the template
**kwargs:
Arguments to the template
'''
# Read the raw template
with open(path, 'r') as f:
string = f.read()
# Convert raw template to template class
template = Template(string)
# Render the template
x = template.render(kwargs)
return x
def send_email(subject, text, html):
'''Sends an email to my work email with contents of `html` (or `text` if recipient turns off html).
Arguments
---------
subject: str
Subject line for email
text: str
A message to email in plain text
html: str
An html message to email
'''
# I've registered my local machine to know what these are
# (Only works if I am logged in on my machine as me)
username = keyring.get_password('airjobs', 'username')
password = keyring.get_password('airjobs', 'password')
if username is None or password is None:
with open('log.txt', 'a') as f:
f.write(f"{datetime.now()}\n")
f.write("\tNo username/password in keyring for `airjobs`\n")
raise ValueError("No username/password in keyring for `airjobs`\n")
# Create the EmailMessage object and assign attributes
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = Address('Christian Million', username, 'gmail.com')
msg['To'] = Address('Christian Million', 'millionc', 'yosemite.edu')
# Add plain text message
msg.set_content(text)
# Alternative added second so it is prioritized when sending
msg.add_alternative(html, subtype='html')
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(username, password)
# If I can't email myself an error message, then I should log it.
except smtplib.SMTPException as e:
with open('log.txt', 'a') as f:
f.write(f"{datetime.now()}\n")
f.write(f"\tSMTP Error {e.smtp_code}: {e.smtp_error}\n")
else:
server.send_message(msg)
finally:
# This will fail is server = smtplib.SMTP("smtp.gmail.com", 587) fails,
# but we will have already logged the error by this point.
server.quit()