Last active
June 18, 2019 12:35
-
-
Save wouter-swierstra/b2f7b4d6307cc8ffd127a82f67e397a5 to your computer and use it in GitHub Desktop.
Sending out email using UU mailservers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import smtplib, ssl, sys, csv, getpass, time | |
# Call this file passing a semi-colon separated csv file as argument, e.g.: | |
# > python notification.py marks.csv | |
# Set debug to False to really send out emails! | |
# Set debug to True prints draft emails to stdout | |
debug = False | |
fromAddress = '[email protected]' | |
username = '[email protected]' | |
subject = 'Resultaat voor Logica voor Informatica' | |
# These variables refer to the index of the column in the csv file from | |
# which you want to extract information | |
toAddressIndex = 1 | |
firstNameIndex = 2 | |
markIndex = 5 | |
# Template for the email body | |
bodyFormat = """ | |
Beste {0}, | |
Je hebt voor je tentamen het volgende cijfer gehaald: | |
Hertentamen: {1} | |
Hier is nog wat uitleg over dit cijfer. | |
Met vriendelijke groet, | |
Wouter | |
Aan deze email kunnen geen rechten worden ontleend. Het officiele | |
cijfer volgt nog via de gebruikelijke kanalen. | |
""" | |
# Template for the email header | |
headerFmt = """To: {0} | |
From: {1} | |
Subject: {2} | |
""" | |
def makeMsgBody(row): | |
toAddress = row[toAddressIndex] | |
header = headerFmt.format(toAddress,fromAddress,subject) | |
name = row[firstNameIndex] | |
mark = "-" | |
if(row[markIndex]): | |
mark = row[markIndex] | |
# extract any further info from the csv file here... | |
# and pass it to the bodyFormat template to assemble the | |
# message body | |
body = bodyFormat.format(name,mark) | |
return (header + body) | |
# Assemble the message and send it | |
def sendmail (server,row): | |
msgBody = makeMsgBody(row) | |
toAddress = row[toAddressIndex] | |
server.sendmail(fromAddress, toAddress, msgBody) | |
# Open the CSV file | |
csvFile = open(sys.argv[1], 'rt') | |
# Connect to the UU server | |
if not debug: | |
password =getpass.getpass('Password:') | |
port=587 | |
try: | |
if not debug: | |
server=smtplib.SMTP('smtp.office365.com',port) | |
server.starttls() | |
server.login(username,password) | |
reader = csv.reader(csvFile,delimiter=';') | |
for row in reader: | |
name=row[firstNameIndex] | |
print ("Sending mail to " + name + "...") | |
if debug: | |
print(makeMsgBody(row)) | |
else: | |
sendmail(server,row) | |
print(".") | |
print("Sent message " + name + "...") | |
if not debug: | |
time.sleep(1) | |
except Exception as e: | |
print(e) | |
finally: | |
csvFile.close() | |
if not debug: | |
server.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment