Daniel
Daniel

Reputation: 671

RDCOMClient (Outlook) - ggplot

I'm using the RDCOMClient library to create an Outlook email. I want to send a ggplot as an image inside the email body (inline), not as an attachment.

The only way I see this as possible is adding the plot as an image inside the HTMLBody property. I tried 2 different methods to add the image in html.

1 - Using the RMarkdown library, I created a html page with the plot. This did not work because the image is encoded as a base64 string, that Outlook does not support.

2 - Saving the ggplot to a file and manually creating a simple html such as: <html><body><img src="**path**/my_plot.png" /></body></html>. This also shows an error instead of the image.

Is there a way to add an image inline?

EDIT:

The second method works on local email, but the receiver's message has an error instead of the actual image.

Upvotes: 4

Views: 1897

Answers (1)

lukeA
lukeA

Reputation: 54277

You could attach the image and reference it in the email body using a content id ("cid"):

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
ggsave(tf<-tempfile(fileext = ".png"), p, dpi = 100, width = 5, height = 5)
library(RDCOMClient)
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
attach <- outMail[["Attachments"]]$Add(tf)
invisible(attach$PropertyAccessor()$SetProperty(
  "http://schemas.microsoft.com/mapi/proptag/0x370E001E", 
  "image/png"
))
invisible(attach$PropertyAccessor()$SetProperty(
  "http://schemas.microsoft.com/mapi/proptag/0x3712001E", 
  cid <- "myggplotimg"
))
outMail[["To"]] = "[email protected]"
outMail[["Subject"]] = "ggplot image"
outMail[["HTMLbody"]] <- sprintf('<p>Here is your image:<br><img src="cid:%s"></p>', cid)
invisible(outMail$Save())
rm(outMail, attach, OutApp)

Upvotes: 2

Related Questions