Skip to content

Instantly share code, notes, and snippets.

@bnjcbsn
Created February 28, 2016 17:00
Show Gist options
  • Save bnjcbsn/70ea55cf8e149f217a3c to your computer and use it in GitHub Desktop.
Save bnjcbsn/70ea55cf8e149f217a3c to your computer and use it in GitHub Desktop.
R send html email with inline images such as plots
So, this works on Windows 7 machine running Outlook 2010 and R 3.2.3 in RStudio.
Two files: testrhtml.rhtml and send_email.R
First is just the default results of creating a new R HTML file with output to testrhtml.html and unnamed-chunk-2-1.png.
Okay, I've really only done this slightly manual and with one plot so far.
***testrhtml.rhtml***
<html>
<head>
<title>Title</title>
</head>
<body>
<p>This is an R HTML document. When you click the <b>Knit HTML</b> button a web page will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>
<!--begin.rcode
summary(cars)
end.rcode-->
<p>You can also embed plots, for example:</p>
<!--begin.rcode fig.width=7, fig.height=6
plot(cars)
end.rcode-->
</body>
</html>
***send_email.R***
library("readr", lib.loc="~/R/win-library/3.2")
eb <- read_lines("testrhtml.html",n_max= -1L)
eb2<-paste(eb, sep="", collapse="")
library(RDCOMClient)
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "benja.jacon@rts.com"
outMail[["subject"]] = "test"
outMail[["BodyFormat"]] <- 2
outMail[["HTMLbody"]] <- eb2
outMail[["Attachments"]]$Add("[replace with forward slash unc to image path]/unnamed-chunk-2-1.png")
# example: outMail[["Attachments"]]$Add("//dfbs0/Home$/bao1/rProj/unnamed-chunk-2-1.png")
outMail$Send()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment