-
Notifications
You must be signed in to change notification settings - Fork 1
/
Emailer.py
70 lines (57 loc) · 2.35 KB
/
Emailer.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
#!python3
# from standard library
from email.mime.text import MIMEText
import logging
import smtplib
import ssl
class Emailer:
'''
Bind settings in a class for reuse
'''
def __init__(self, settings):
self.settings = settings
def send(self, to, subject, body):
"""
Send an email using the configured settings.
params:
to - The email address to which to send the email.
can be a string for 1 recipient or an array for multiple recipients
subject - The subject for the email
body - The message body for the email
"""
message = MIMEText(body)
message['From'] = self.settings['from_address']
if(type(to) == str):
message['To'] = to
else:
message['To'] = ", ".join(to)
if 'cc_address' in self.settings:
message['Cc'] = self.settings['cc_address']
if 'bcc_address' in self.settings:
message['Bbc'] = self.settings['bcc_address']
message['Subject'] = subject
if 'reply_to' in self.settings:
message.add_header('reply-to', self.settings['reply_to'])
server = smtplib.SMTP(self.settings['smtp_server'], int(self.settings['smtp_port']))
context = ssl.create_default_context()
if 'my_smtp_server_uses_a_weak_certificate' in self.settings:
if self.settings['my_smtp_server_uses_a_weak_certificate'].lower() in ("yes", "true", "1"):
context.set_ciphers('HIGH:!DH:!aNULL')
server.starttls(context=context)
server.login(self.settings['auth_user'], self.settings['auth_password'])
server.send_message(message)
server.quit()
logging.info("Emailed: %s about: %s", to, subject)
# Rest of this file is the test suite. Use `python3 Email.py` to run
# check prevents running of test suite if loading (import) as a module
if __name__ == "__main__":
# standard library
import configparser
# Init logging
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
# Read our Configuration
settings = configparser.ConfigParser()
settings.read('config.ini')
# connect to backend database
emailer = Emailer(settings['email'])
emailer.send(settings['email']['cc_address'], "Hello World", "Greetings Developer. You have tested the Emailer module.")