sendmailR (Part2): Sending files as mail attachments

George Dontas picture George Dontas · Aug 26, 2010 · Viewed 13.5k times · Source

Following the directions provided in this related question, I was able to send html formated mail messages. Now the question is this: How should I modify the following code, in order to attach one or more files (of any type) to this message?

library(sendmailR)

from <- "<[email protected]>"
to <- c("<[email protected]>","<[email protected]>")
subject <- iconv("Message Title", to = "utf8")

msg <- "<hr size='2' width='33%' style='text-align: left;'><font size='2'>
  <i>This email was sent automatically using <a href='http://finzi.psych.upenn.edu/R/library/sendmailR/html/00Index.html' rel='nofollow' target='_blank'>sendmailR</a>.<br>
  Please do not reply directly to this e-mail.</i></font>"

msg <- iconv(msg, to = "utf8")

sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))

Answer

Rahul Premraj picture Rahul Premraj · May 8, 2014

With the mailR package (https://github.com/rpremraj/mailR), you could send HTML emails and additionally attach files with ease as below:

send.mail(from = "[email protected]",
          to = c("[email protected]", "[email protected]"),
          subject = "Subject of the email",
          body = "<html>The apache logo - <img src=\"http://www.apache.org/images/asf_logo_wide.gif\"></html>",
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
          attach.files = c("./download.log", "upload.log"),
          authenticate = TRUE,
          send = TRUE)

Edit (2014-05-13):

mailR has been updated to allow different character encodings. Below is an example to send the message as UTF-8.

send.mail(from = "Sender Name <[email protected]>",
          to = "[email protected]",
          subject = "A quote from Gandhi",
          body = "In Hindi :  थोडा सा अभ्यास बहुत सारे उपदेशों से बेहतर है।
                  English translation: An ounce of practice is worth more than tons of preaching.",
          encoding = "utf-8",
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = T),
          authenticate = TRUE,
          send = TRUE)