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.


  1. Cool post. When I tried the code, I get

    Error in wait_for(code) :
    SMTP Error: 5.7.1 : Relay access denied

    Perhaps it's an issue with my setting for the smtpServer or because I'm behind a firewall.
    Any ideas?

    1. Note that Google removed the email address that appears in between "5.7.1:" and "Relay access denied" in the error message as part of its spam filter.

    2. Jeromy....I am not sure what is causing this, but I agree that it is likely an issue with firewall or some SMTP settings. I hope you can figure it out.

    3. It must have been a problem with network settings at work. Your examples worked fine when I tried it at home. Thanks.