Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending R Markdown output as body email via outlook (RDCOMclient)

Just learning R Markdown language and wondering if I can send the output in body email via outlook from R (using RDCOMClient; my office don't use gmail)

Thank you

like image 297
edit_profile Avatar asked Oct 25 '16 10:10

edit_profile


2 Answers

Building upon Ben's answer, the strange symbols showing up everywhere are probably being caused by a enconding mismatch between R and Outlook Object (created by the RDCOMClient Library).

Outlook's basic encoding is "UTF-16", while the basic RMarkdown input is in "UTF-8". To make sure your html output generated by RMarkdown is in "UTF-8" write:

knitr::knit("tale_email_body.Rmd", encoding = "UTF-8")  
eb <- read_lines("tale_email_body.html",locale =  locale(encoding = "UTF-8"))     
Encoding(eb)

You should see a vector whose entries are "UTF-8" or "unknown". Next you have to convert the encoding to the right format using:

eb2 <- paste(eb, sep="", collapse="") 
eb2 <- iconv(eb2, from = "UTF-8",to= "Latin1")

You should them be able to send emails without strange symbols using Ben's code:

library(RDCOMClient)

olMailItem <- 0
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(olMailItem)

# this retains default Outlook signature
outMail$GetInspector()
signature <- outMail[["HTMLBody"]]

outMail[["To"]] <- sm
outMail[["CC"]] <- paste("egrp",dm,sep=";")
outMail[["subject"]] <- "note this"
outMail[["BodyFormat"]] <- 2
outMail[["HTMLbody"]] <- paste0(eb2, signature)
outMail$Display()
outMail$Send()
like image 184
Luis Bento Avatar answered Nov 15 '22 06:11

Luis Bento


Short answer:

Create .Rhtml file for email body.

Knit it and read it:

knitr::knit("tale_email_body.Rhtml")  
library("readr", lib.loc="~/R/win-library/3.2")
eb <- read_lines("tale_email_body.html",n_max= -1L)
eb2<-paste(eb, sep="", collapse="") 

Use results in email body:

library(RDCOMClient)

olMailItem <- 0
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(olMailItem)

# this retains default Outlook signature
outMail$GetInspector()
signature <- outMail[["HTMLBody"]]

outMail[["To"]] <- sm
outMail[["CC"]] <- paste("egrp",dm,sep=";")
outMail[["subject"]] <- "note this"
outMail[["BodyFormat"]] <- 2
outMail[["HTMLbody"]] <- paste0(eb2, signature)
outMail$Display()
outMail$Send()

Let me know if you have questions or improvements.

Partial Credit to: How to add my Outlook email signature to the COM object using RDCOMClient

like image 1
Ben Jacobson Avatar answered Nov 15 '22 06:11

Ben Jacobson