Email from R -- with attachments

Has anyone successfully bulk-emailed from R, with attachments? This guide -- by Jenny Bryan is amazing (for sending emails with gmailr), but I'm struggling to figure out how to write something that works with (multiple) attachments :confused: I haven't had great luck with the mailr and sendmailr packages, alack, and ended up going a very strange route using the googledrive package and Google Mail Merge (generating "send-sheets" with G-drive links).

Any pointers/approaches anyone could recommend? If it isn't obvious, I'm pretty new to coding, and this is more about figuring out where to look/ how to think about it :slight_smile:

Best!

1 Like

Attachments and in-line graphics would be GREAT. I've managed to string together a bunch of tables produced by the tableHTML package and send them with:

html_msg <- mime() %>%
  to(gmail_to_list) %>%
  from(my_address) %>%
  subject(paste("activity as of", week_end)) %>%
  html_body(paste(
    "<h2>Enrollment and staffing statistics as of", week_end, "</h2><br>",
    if (nrow(starting_soon) == 0) {
      "<h3>There are no classes that are starting up at this point.</h3><br><br>"
    } else {
      paste("<h3>These classes start between ", as.Date(as.POSIXct(today() - 7)) ,
            " and ", as.Date(as.POSIXct(today() + 14)) , ":</h3><br>",
            starting_soon_table, "<br><br>")
    },  # etc., etc.
    my_footer
  )    )

draft_id <- create_draft(html_msg)
send_draft(draft_id)

It would be wonderful to have a bullet-proof, scheduled way to generate emails with a complex mix of elements.

2 Likes

I've never done it myself, but I once saw a presentation by Jared Lander called R For Everything, where he emailed from R. You could you search for his resources. Sorry I can't be more helpful!

1 Like

Ok at core, this works -- thank you for the comments!

library(gmailr)
library(dplyr)
library(magrittr)

body_text <- "I think this will work now!" 

test <- mime() %>%
  to(recipient) %>%
  from(sender) %>%
  subject("This is a test") %>%
  html_body(body_text) %>%
  attach_part(body_text)%>%
  attach_file(attachment1) %>%
  attach_file(attachment2) 

create_draft(test)
#send_message(test)

Sources:

(1) https://cran.r-project.org/web/packages/gmailr/vignettes/sending_messages.html
-- ^there was an issue here with getting the email-body to show up. But source 2 (below) shows one way to solve that, which I incorporated in the code above.
(2) https://github.com/jimhester/gmailr/issues/60

Next steps: Purrr :0

2 Likes

I added a comment on github, showing what I found to be the limits. Bottom line for me, I did succeed in sending 2 attachments but no body text. See the code snippet that shows what works for me:

https://github.com/jimhester/gmailr/issues/60