4

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.

Daniel
  • 639
  • 8
  • 24

1 Answers1

2

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"]] = "johndoe@example.com"
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)
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • It's a bit easier actually. You don't have to set the attachment property. If you set the cid in your HTMLBody with the image name (including the extension) it works. – Daniel Apr 30 '18 at 13:24
  • How would this be done with multiple images embedded in the email? I've been trying to apply this concept to 2 images, but unsuccessful so far. – georgemirandajr Mar 11 '20 at 20:05