How to send an email with attachment from R in windows

ahala picture ahala · May 21, 2010 · Viewed 47.9k times · Source

I have a scheduled an R script running from a windows machine.

After it finishes, I wish this script to automatically send an email with some log file attached.

Using shell() with some other scripts may be possible, but I was wondering if there is a better solution within R. Thanks.

Answer

ARobertson picture ARobertson · Feb 3, 2012

sendmailR works for me on Windows 7. I referenced http://cran.es.r-project.org/web/packages/sendmailR/sendmailR.pdf

smtpServer= info for Outlook 2010 is in File -> Account Settings -> Account Settings -> double click your account -> text in "Server" box

library(sendmailR)

#set working directory
setwd("C:/workingdirectorypath")

#####send plain email

from <- "[email protected]"
to <- "[email protected]"
subject <- "Email Subject"
body <- "Email body."                     
mailControl=list(smtpServer="serverinfo")

sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)

#####send same email with attachment

#needs full path if not in working directory
attachmentPath <- "subfolder/log.txt"

#same as attachmentPath if using working directory
attachmentName <- "log.txt"

#key part for attachments, put the body and the mime_part in a list for msg
attachmentObject <- mime_part(x=attachmentPath,name=attachmentName)
bodyWithAttachment <- list(body,attachmentObject)

sendmail(from=from,to=to,subject=subject,msg=bodyWithAttachment,control=mailControl)

In addition, multiple files can be sent by adding another mime_part to the msg list as follows (I also condensed it):

attachmentObject <- mime_part(x="subfolder/log.txt",name="log.txt")
attachmentObject2 <- mime_part(x="subfolder/log2.txt",name="log2.txt")
bodyWithAttachment <- list(body,attachmentObject,attachmentObject2)