9

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
edit_profile
  • 147
  • 2
  • 7
  • This might help: http://stackoverflow.com/questions/26811679/sending-email-in-r-via-outlook or maybe sendmailR? http://stackoverflow.com/questions/2885660/how-to-send-email-with-attachment-from-r-in-windows – Stedy Dec 24 '16 at 22:51

2 Answers2

3

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()
Luis Bento
  • 56
  • 4
1

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

Ben Jacobson
  • 83
  • 1
  • 9
  • 1
    This sort of worked for me but didn't retain a lot of the formatting in my html file, and also resulted in strange symbols showing up everywhere (for example, in place of an apostrophe). – Nova Sep 20 '17 at 15:10