How to send R markdown report in body of email?

前端 未结 2 870
南旧
南旧 2021-01-30 04:21

update: Brandon Bertelsen\'s answer:

Brandon\'s answer produces the following output. It doesn\'t produce nice tables or highlight code like Rstudio do

2条回答
  •  后悔当初
    2021-01-30 04:37

    The main problem is that email readers strip your code and don't allow external imports. To get basic CSS support, the best strategy is to use inline styles to have a consistent view. We'll circle back to that in a minute.

    First, you have to setup your Rmd document a little differently so it excludes all the extra javascript files. theme, highlight and mathjax should all be null. Notice, I've added a css attribute.

    ---
    title: "Report for email"
    output: 
      html_document: 
        self_contained: no
        theme: null
        highlight: null
        mathjax: null
        css: ink.css
    ---
    
    ```{r}
    summary(cars)  
    ```
    
    You can also embed plots, for example:
    
    ```{r, echo=FALSE}
    plot(cars)
    ```
    

    ink.css comes from http://foundation.zurb.com/emails. I recommend using this as your base theme.

    There are a number of different scripts you can use to "inline" your css (that's a verb), I've included instructions here for using premailer a python package. Unfortunately, none of them will support very complicated CSS like bootstrap. So you'll just have to make do with your own style built up using ink or whatever as your foundation.

    You may need to install some elements, for me on Ubuntu:

    sudo apt-get install python-pip libxslt1-dev
    sudo pip install premailer
    

    Now, you can do something like this.

    library(rmarkdown)
    library(mailR)
    rmarkdown::render("example.Rmd")
    system("python -m premailer -f example.html -o output.html")
    
    
    send.mail(
      from = "me@gmail.com",
      to = "me@gmail.com",
      subject = "R Markdown Report - rmarkdown",
      html = T,
      inline = T,
      body = "output.html",
      smtp = list(
         host.name = "smtp.gmail.com", 
         port = 465, 
         user.name = "me",    
         passwd = "password", 
         ssl = T),
      authenticate = T,
      send = T)
    

    DISCLAIMER: Your mileage may vary wildly depending on which email reader is your target

提交回复
热议问题