Skip to content

Instantly share code, notes, and snippets.

@Lakens
Created September 2, 2018 13:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Lakens/3643c1f327a8ee7bfc67469e2d708e98 to your computer and use it in GitHub Desktop.
Save Lakens/3643c1f327a8ee7bfc67469e2d708e98 to your computer and use it in GitHub Desktop.
Emailing students from R using mailR package
#Load packages
library(readxl)
library(mailR)
#Read student data
info <- read_excel("student_names_email.xls",
sheet = 1,
col_names = TRUE)
#Loop from 1 to the number of email addresses in the spreadsheet
for (i in 1:length(info$Email)) {
print(i) #print current progress (because it takes a while and it's god to ee how many emails have been sent)
#get data from one of the rows
temp_data <- info[i,]
#Get email address for the student
#Check the column numbers in your dataset! In mine, emails are in column 7, first names in column 4, grades in column 6
current_email <- temp_data[1,7]
# personalized emails
text <- paste("<!DOCTYPE html><html><body><p>",
"Dear ",temp_data[1,4],",",
"<p>Your grade for the exam has been calculated.</p>",
"<p>You can find your grade printed below:</p>",
"<p>Exam Grade: ", temp_data[1,6],"</p>",
"<p>Best regards,<br><br>Dr. Daniel Lakens</p>",
"<p style='font-family:Calibri;'>---------------------------------------------------<br>",
"</body></html>",
sep="")
if (is.na(current_email) == FALSE) { #checks if there was an email address in the row in our spreadsheet
email <- send.mail(from = "D.Lakens@tue.nl",
to = current_email,
#cc = "D.Lakens@tue.nl", #uncomment this line to cc someone on every email
subject = "Grade for Intro Psych",
body = text,
html = TRUE,
#attach.files = paste("C:\\Users\\Name\\report_", temp_data[1,4], ".doc", sep = ''), #You can also attach files to the email - for example a file named based on the students' ID number. You can also first create these files in R markdown and then send them!
smtp = list(host.name = "smtp.yourdomain.com",
port = 1234, #(often 2525)
user.name = "Login", #The log in name for your email
passwd = "password123", #Your password
tls = TRUE),
authenticate = TRUE,
send = TRUE)
}
#If you send hundreds of emails, your emails server will stop (it assumes your computer is sending out spam)
#Building in a short wait time prevents this - you can play around with the time you needs to wait
Sys.sleep(10) #wait 10 seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment