update: Brandon Bertelsen's answer :
布兰登的答案产生以下输出 . 它不会像Rstudio那样产生漂亮的表格或突出显示的代码,并且它会在一些带有unicode的html文件上崩溃,所以我没有用它来自动化我的电子邮件报告 .
我目前的方法是使用Rstudio编译为html,在chrome中打开html文档,然后将html文档复制并粘贴到gmail中 . 这很好用,看看这个要点:https://gist.github.com/nelsonauner/a68b5a808c232ce7817e
原始问题:
是否有一种简单的方法可以将R降价文档作为电子邮件的正文发送,以便电子邮件的正文与使用Rstudio的“编织HTML”的结果类似?
这是使用 knitr
, rmarkdown
和 mailR
的基本可重现示例
example.Rmd
---
title: "Report for email"
output:
html_document:
self_contained: no
---
```{r}
summary(cars)
You can also embed plots, for example:
plot(cars)
我正在使用 `self_contained: no` ,因为默认的base64编码不适用于 `mailR` (Yihui在[this SO post](https://stackoverflow.com/questions/32520928/in-r-is-there-any-way-to-send-an-rmarkdown-v2-html-file-as-the-body-of-an-email)推荐)
## knit_and_send.R
```java
# compile using rmarkdown
library(rmarkdown)
rmarkdown::render("example.Rmd")
library(mailR)
send.mail(from = "me@gmail.com",
to = "me@gmail.com",
subject = "R Markdown Report - rmarkdown",
html = T,
inline = T,
body = "example.html",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "me", passwd = "password", ssl = T),
authenticate = T,
send = T)
#compile using knitr
library(knitr)
knit2html("example.Rmd",options="")
send.mail(from = "me@gmail.com",
to = "me@gmail.com",
subject = "R Markdown Report - knitr",
html = T,
inline = T,
body = "example.html",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "me", passwd = "password", ssl = T),
authenticate = T,
send = T)
两封电子邮件都成功发送 .
针织电子邮件看起来像这样:
并且rmarkdown电子邮件看起来像这样 . (请注意,它还包含一堆javascript文件 - 我想我必须编写一些脚本来删除它们)
但是它们都不像Rstudio的“Knit as HTML”生成的报告那样好看,它看起来像这样:
有什么建议?
我认为一个真正的修复可能涉及一些html文件的后处理,它以一种电子邮件友好的方式结合css样式,同时删除javascript文件 .
现在,我将使用 knitr
包 .
如果问题不清楚,请告诉我,我会改进这个问题 .
相关的SO帖子:
In R is there any way to send an RMarkdown v2 html file as the body of an email
1 回答
主要问题是电子邮件阅读器剥离您的代码并且不允许外部导入 . 要获得基本的CSS支持,最好的策略是使用内联样式来获得一致的视图 . 我们将在一分钟内回过头来 .
首先,您必须以不同的方式设置Rmd文档,以便排除所有额外的javascript文件 .
theme
,highlight
和mathjax
应该都是null
. 注意,我添加了一个css
属性 .You can also embed plots, for example:
现在,你可以做这样的事情 .
免责声明:根据您的目标电子邮件阅读器,您的里程可能会有很大差异