-
Notifications
You must be signed in to change notification settings - Fork 6
/
mail_utils.py
94 lines (73 loc) · 2.91 KB
/
mail_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
90
91
92
93
94
# -*- coding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from random import shuffle, randint
import smtplib
import yaml
import json
import ssl
def email_meta_loader() -> dict:
"""Utility function to load email parameters."""
with open('_config.yml') as config:
meta = yaml.load(config, Loader=yaml.FullLoader)
return meta
def load_emails(emails_path : str) -> list:
"""Utility function to load emails list."""
with open(emails_path) as emails_file:
emails = json.load(emails_file)
return emails
def assign_partner(emails : list) -> list:
"""Utility function to match partners from emails list."""
n = len(emails)
if n < 2:
raise ValueError(f'List must have at least 2 emails, it has {n} elements')
shuffle(emails)
start = 0
while start < n - 1:
# Choose the cut for the cycle
cut = randint(start + 2, n - 1) if start + 2 < n - 1 else n
if cut == n - 1: cut = n
# Assign the cycle
for i in range(start, cut):
emails[i]['assigned'] = emails[(i + 1) % cut]['name']
# Reset the range
start = cut
# Make sure all emails are assigned to only one person. If not, repeat the shuffling until
# this is done:
not_true = True
while not_true:
master_dict = {}
not_true = False
for i in range(n):
if emails[i]['assigned'] not in master_dict.keys():
master_dict[emails[i]['assigned']] = 1
else:
not_true = True
assign_partner(emails)
break
return emails
def send_email(email : dict, user : dict) -> None:
"""Utility function to send email to a specific user."""
# Setup email configurations:
message = MIMEMultipart('alternative')
message['Subject'] = email['subject']
message['From'] = email['email']
message['To'] = user['email']
# Load email body:
with open(email['body']) as body:
html = body.read()
html = html.format(user['name'], user['assigned'])
body = MIMEText(html, 'html')
message.attach(body)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
server.login(email['email'], email['password'])
server.sendmail(
email['email'], user['email'], message.as_string()
)
if __name__ == "__main__":
email = email_meta_loader()
emails = load_emails(email['list'])
assign_partner(emails)
print(emails)