Batch emailing a CSV file of data using Python and SMTP

A quick script for sending a batch of emails using a csv file. Each csv line contains an email address and the information I wish to populate in the email content and send to a single recipient. In this case, I wanted to send grades out for a group of students using a spreadsheet of grades from Google docs (and with my Gmail). With cursory preprocessing, I put the data in this format:

 Firstname1 Lastname1,userID1,91.7,0.979
 Firstname2 Lastname2,userID2,60.8,0.061
 ...

Then, we can parse it and fire off our mailer with the following:

# erik reed
import smtplib
import csv
from time import sleep
from email.mime.text import MIMEText
 
FROM_ADDRESS = "[email protected]"
SMTP_SERVER = 'smtp.gmail.com:587'
SMTP_USER = "ADD_ME"
SMTP_PASS = "ADD_ME"
 
def mail(msg):
  server = smtplib.SMTP(SMTP_SERVER)
  server.starttls()
  server.login(SMTP_USER,SMTP_PASS)
  server.sendmail(FROM_ADDRESS, msg['To'], msg.as_string())
  server.quit()
 
f = open('grades.csv')
reader = csv.reader(f)
for row in reader:
  content = 'Hi ' + row[0].strip().split(' ')[0]
  content += \
''',\n\nThis is an automated message with your final exam grade. If
you have any questions regarding exam grade, see ***** if you
are in SV, otherwise talk to me. The average grade on the final
exam was 76% with a standard deviation of 12.5%.\n\n'''
  content += 'You received a ' + str(row[2]) + '%, corresponding to '
  content += 'the ' + str(float(row[3]) * 100) + 'th percentile.'
  content += '\n\nErik'
 
  msg = MIMEText(content)
  msg['To'] = row[1] + '@cmu.edu'
  msg['From'] = FROM_ADDRESS
  msg['Subject'] = 'Fastcode: exam grade for ' + row[1]
  msg.add_header('reply-to', FROM_ADDRESS)
  print msg.as_string()
 
  mail(msg)
  sleep(1) # pause after each email send
f.close()

This could be cleaned up a bit using better Python syntax, but it does the trick. Each email will look something like the following:

Hi Firstname1,

 

This is an automated message with your final exam grade. If
you have any questions regarding exam grade, see ***** if you
are in SV, otherwise talk to me. The average grade on the final
exam was 76% with a standard deviation of 12.5%.

You received a 45%, corresponding to the 2.0th percentile.

 

Erik

2 Responses to “Batch emailing a CSV file of data using Python and SMTP”

  1. Anonymous

    Since you were already using Google Docs and Gmail, would it have been simpler to use Google Apps Script?

Leave a Reply