-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmail.py
executable file
·103 lines (78 loc) · 2.57 KB
/
mail.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
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python3
import argparse
import csv
import os
import smtplib
import sys
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
"""
expects a csv file with assignments of the form:
uni,name,seat
name is ignored. Email is sent to [email protected].
"""
# Creates a CLI argument parser
parser = argparse.ArgumentParser()
parser.add_argument("filename",
type=str,
help="filename of the seating chart",
metavar='<filename>')
parser.add_argument("-a", "--from_addr",
type=str,
default="[email protected]",
help="the email address of the sender",)
parser.add_argument("-s", "--subject",
type=str,
default='',
help='subject line for the emails sent, default is no subject')
parser.add_argument("-n", "--sender",
type=str,
default='3157 Teaching Staff',
help='sender name for emails, default="3157 Teaching Staff"')
parser.add_argument("-r", "--reply_to",
type=str,
default='[email protected]',
help='reply-to email address, default="[email protected]"')
args = parser.parse_args()
#the message template, takes one variable which is replaced with the seat number
msg = "You are assigned seat %s."
filename = args.filename
file = open(filename)
students = csv.reader(file)
def setup_server():
server = smtplib.SMTP("smtp-relay.gmail.com", 587)
server.starttls()
return server
server = None
DEFAULT_BACKOFF = 30 # seconds
next_backoff = DEFAULT_BACKOFF
for uni, to_name, seat in students:
print(uni, msg % seat)
to_columbia = f"{uni}@columbia.edu"
to_barnard = f"{uni}@barnard.edu"
recipients = [to_columbia, to_barnard]
email = MIMEMultipart()
email["From"] = f"\"{args.sender}\" <{args.from_addr}>"
email["To"] = ", ".join(recipients)
email["Subject"] = args.subject
email["Reply-To"] = args.reply_to
body = msg % seat
email.attach(MIMEText(body, "plain"))
text = email.as_string()
while True:
try:
if server == None:
server = setup_server()
server.sendmail(args.from_addr, recipients, text)
time.sleep(1)
next_backoff = DEFAULT_BACKOFF
break
except (smtplib.SMTPException, smtplib.SMTPServerDisconnected) as e:
print(f"{e.smtp_code}: {e.smtp_error.decode()}")
print(f"Waiting {next_backoff} seconds")
time.sleep(next_backoff)
next_backoff *= 2
server = None
file.close()
server.quit()