|
| 1 | +import smtplib |
| 2 | +from email.mime.text import MIMEText |
| 3 | +from email.mime.multipart import MIMEMultipart |
| 4 | + |
| 5 | +from templates import Template |
| 6 | +# environment variables |
| 7 | + |
| 8 | +password = '<your password>' |
| 9 | + |
| 10 | +class Emailer(): |
| 11 | +subject = "" |
| 12 | +context = {} |
| 13 | +to_emails = [] |
| 14 | +has_html = False |
| 15 | +test_send = False |
| 16 | +from_email = 'Hungry Py <[email protected]>' |
| 17 | +template_html = None |
| 18 | +template_name = None |
| 19 | + |
| 20 | +def __init__(self, subject="", template_name=None, context={}, template_html=None, to_emails=None, test_send=False): |
| 21 | +if template_name == None and template_name == None: |
| 22 | +raise Exception("You must set a template") |
| 23 | +assert isinstance(to_emails, list) |
| 24 | +self.to_emails = to_emails |
| 25 | +self.subject = subject |
| 26 | +if template_html != None: |
| 27 | +self.has_html = True |
| 28 | +self.template_html = template_html |
| 29 | +self.template_name = template_name |
| 30 | +self.context = context |
| 31 | +self.test_send = test_send |
| 32 | + |
| 33 | +def format_msg(self): |
| 34 | +msg = MIMEMultipart('alternative') |
| 35 | +msg['From'] = self.from_email |
| 36 | +msg['To'] = ", ".join(self.to_emails) |
| 37 | +msg['Subject'] = self.subject |
| 38 | + |
| 39 | +if self.template_name != None: |
| 40 | +tmpl_str = Template(template_name=self.template_name, context=self.context) |
| 41 | +txt_part = MIMEText(tmpl_str.render(), 'plain') |
| 42 | +print(txt_part) |
| 43 | +msg.attach(txt_part) |
| 44 | +if self.template_html != None: |
| 45 | +tmpl_str = Template(template_name=self.template_html, context=self.context) |
| 46 | +html_part = MIMEText(tmpl_str.render(), 'html') |
| 47 | +print(html_part) |
| 48 | +msg.attach(html_part) |
| 49 | +msg_str = msg.as_string() |
| 50 | +return msg_str |
| 51 | + |
| 52 | +def send(self): |
| 53 | +msg = self.format_msg() |
| 54 | +# login to my smtp server |
| 55 | +did_send = False |
| 56 | +if not self.test_send: |
| 57 | +with smtplib.SMTP(host='smtp.gmail.com', port=587) as server: |
| 58 | +server.ehlo() |
| 59 | +server.starttls() |
| 60 | +server.login(username, password) |
| 61 | +try: |
| 62 | +server.sendmail(from_email, to_emails, msg_str) |
| 63 | +did_send = True |
| 64 | +except: |
| 65 | +did_send = False |
| 66 | +return did_send |
| 67 | +# with smtplib.SMTP() as server: |
| 68 | +# server.login() |
| 69 | +# pass |
0 commit comments