Adding an Email button in Shiny, using TableTools

2019-02-25 16:10发布

问题:

The code below produces a DataTable output that I'd like to have it emailed using an Email button, similar to the Export button created below. Is there an easy way to add a button so that when you click, it pops up Microsoft Outlook to send the datatable as an attachment, say in csv format?

Also, please click here and here to help with a similar questions.

#Load required packages
require(shiny)

#Create a dataframe
df <- data.frame(random=1:160)

server <- function(input,output,session){

    #Display df using DataTable and apply desired options
    output$display <- renderDataTable({df}, 
           option=list(pageLength=100,
                       "dom" = 'T<"clear">lfrtip',
                       "tableTools" = list(
                        "sSwfPath" = "//cdn.datatables.net/tabletools/2.2.3/swf/copy_csv_xls_pdf.swf",
                        "aButtons" = list(list("sExtends" = "csv","oSelectorOpts"=list("page"="all"),"sButtonText" = "Export","aButtons" ="csv")))         
       )

   )
}

ui <- shinyUI(fluidPage(

    #Add a title
    h1('Testing TableTools'),

    #Add required JS libraries
    tagList(
        singleton(tags$head(tags$script(src='//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js',type='text/javascript'))),
        singleton(tags$head(tags$script(src='//cdn.datatables.net/tabletools/2.2.3/js/dataTables.tableTools.min.js',type='text/javascript'))),
        singleton(tags$head(tags$link(href='//cdn.datatables.net/tabletools/2.2.3/css/dataTables.tableTools.css',rel='stylesheet',type='text/css')))
            ),


        mainPanel(
           #Display results
           dataTableOutput('display')
                 )      


))

shinyApp(ui = ui, server = server)

回答1:

A quick way is to use mailto(which works well with Outlook).

The mailto would need to be inside an HTML() tag for shiny to render it.

HTML(
<a href="mailto:hello@rshiny.com?
body='Hello,World!  Check out my data.'
&subject='Data'
&attachment='\\myfolder\shinyData.csv'">click here for email!</a>
)

There are two hypothetical ways to do this.

  1. Have the mailto in ui.R

The code would need to download the datatable at the user's end (probably in the temp folder), and attach it there.

  1. Have the mailto in server.R

You'll need the csv file already saved on your server in order to load it as an attachment. You would need to use the above code inside a renderUI() and also pass the file from your server to the user's end.

There is a downloadHandler() function which allows users to download from the server which could be of use for the above.

I've never tried passing attachments around as you are trying, however the above logic should both allow you to create an email, and get you on the right path to attaching files.