Wednesday, May 30, 2012

Send emails with attachments from R command line

The sendmailR package makes it easy to send emails with attachments from the R command line. 

#load package

#use string formatting and your system info to format FROM address
from <- sprintf("<Project1@%s>",[4])
to <- "<>"
subject <- "Test Email From R"
#create list with text of body as first element
#second list element is R object to attach using the mime_part() function
body <- list("Email sent from R. Dataframe attached.",mime_part(data.frame(x=rnorm(1000),y=rnorm(1000)),name="output"))

sendmail(from, to, subject, body, control=list(smtpServer="ASPMX.L.GOOGLE.COM"))

Why would you want to do this, you ask?  Suppose you are doing some lengthy simulations and you need to do other things while they are running.  Just code up an email to be sent alerting you when they are finished. 

It is also a nice way to export data computed during an R session by sending it to your webmail account.  You can change the from address from Project1 (as in example code above) to something more meaningful for a specific project, then set up an email filter to organize your output emails.  The useful possibilities are numerous.