I have a dataframe as shown below. I am then converting the dataframe into an html table.
# Use RDCOMClient to send email from outlook
library(RDCOMClient)
# Use xtable to convert dataframe into html table
library(xtable)
# Create dataframe
df <- as.data.frame(mtcars[1:3,1:3])
# Create HTML object
df_html <- xtable(df)
Now, I am sending an email from outlook using the wonderful solution given in the email thread Sending email in R via outlook
## init com api
OutApp <- COMCreate("Outlook.Application")
## create an email
outMail = OutApp$CreateItem(0)
## configure email parameter
outMail[["To"]] = "dest@dest.com"
outMail[["subject"]] = "some subject"
outMail[["body"]] = df_html
## send it
outMail$Send()
For the body of my email, I want the data frame df which I want to attach as a html table. When I execute the above code, I get the below error message.
Error in `[[<-`(`*tmp*`, "body", value = list(mpg = c(21, 21, 22.8), cyl = c(6, :
Can't attach the RDCOMServer package needed to create a generic COM object
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘RDCOMServer’
When I change the line outMail[["body"]] = df_html
to outMail[["body"]] = paste0(df_html)
, I get the email but the output does not come as a table. It comes as shown below in my outlook.
c(21, 21, 22.8), c(6, 6, 4), c(160, 160, 108)
I want this to be a table. How can i achieve this? Thanks!
I finally found a solution to pasting a dataframe as an HTML table in Microsoft outlook. This is using the xtable
package. Part of the solution credit goes to @lukeA from here - How to show an excel worksheet in outlook body by R
Below is the solution.
library(RDCOMClient)
library(xtable)
x <- head(mtcars)
y <- print(xtable(x), type="html", print.results=FALSE)
body <- paste0("<html>", y, "</html>")
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "TEST EMAIL"
outMail[["HTMLbody"]] = body
outMail$Send()
This is how the output looks like in Microsoft outlook.