How to Send Custom E-mails with R

[This article was first published on R Views, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A common business oriented data science task is to programatically craft and send custom emails. In this post, I will show how to accomplish this with R on the RStudio Connect platform (a paid product built for the enterprise) using the blastula package.blastula provides a set of functions for composing high-quality HTML e-mails that render across various e-mail clients, such as gmail and outlook, and also includes tooling for sending out those e-mails via SMTP, the standard protocol for electronic mail transmission between different e-mail providers. At the bottom of the post you can find a link to documentation showing how to publish email with blastula via an SMTP server without using RStudio Connect.

As an example, we’ll pretend that I work in a marketing analytics department at an insurance company. I’m responsible for a marketing report, which I used the rmarkdown package to create, that tracks the number of bound policies from different marketing activities:

## Warning: package 'tibble' was built under R version 3.5.2
## Warning: package 'knitr' was built under R version 3.5.2
Mktg_Activity Policies Target
Partnerships 345 320
E-mail Mktg 434 410
Direct Mail 240 235
Radio 128 100

Having written the report with R Markdown, I will publish the script to RStudio Connect and have Connect create and send the e-mail for me. Once this is done, I’ll turn on both the scheduler and Send email after update options to have Connect re-run the report on a set schedule. By default, the e-mail generated by RStudio Connect looks something like this:

 

Because we haven’t done anything to customize the e-mail notification yet, Connect generated a standard out-of-the-box e-mail. It used the published document name for the e-mail subject, included a link to the report, as well as the time stamp of when it was executed. The e-mail also contains the actual report as an attachment, which can be downloaded and viewed. This is already useful, but in this case I’d like to customize the e-mail to make it more tailored to fit my team’s needs. This is where the blastula package comes in.

blastula allows you to create and send e-mails using R. It works similarly to the Shiny package, but instead of writing R code to create an interactive application, you write R code to create an HTML e-mail that can be rendered across a wide variety of e-mail providers. Once you’ve programmatically created an HTML e-mail, bastula can also be used to send out that e-mail programmatically.

To create your custom e-mail, simply add a new R code chunk at the bottom of your R Markdown script. You can use the code chunk option include = FALSE so that your R code isn’t printed in your actual RMardown report, since that wouldn’t be very helpful to whoever is reading the report:

# load the blastula package
library("blastula")

# create a simple e-mail
email <- compose_email(body = "Insert your e-mail body here",
                       footer = "Insert your e-mail footer here")

# preview e-mail in Viewer pane
preview_email(email)

 

blastula supports string interpolation, meaning it can display the value of an R variable rather than simply printing your R code as regular old text. The way to tell blastula what’s R code, vs. what’s just text, is by adding curly braces around anything you want to be interpreted as R:

# create an e-mail with R code

email_body <- 
"
Hi! This new report was generated at {Sys.time()}
"

email_footer <- 
"
Please contact *[email protected]* with any questions
"

email <- compose_email(body = email_body,
                       footer = email_footer)

# preview e-mail in Viewer pane
preview_email(email)

 

You’ll notice that not only can you include R code, but you can also supply Markdown text (notice how we italicized some of the footer text). In addition to all this, you can also use helper functions included in the blastula package to add other elements to your e-mail. For example, you can add a ggplot2 plot as an image using the add_ggplot function:

# create an e-mail with a plot
library(ggplot2)
plot <- ggplot(tb, aes(Mktg_Activity, Policies)) + geom_bar(stat = "identity")


email_body <- 
"
Hi! This new report was generated at {Sys.time()} \\


{add_ggplot(plot, width = 5, height = 3)}

"

email_footer <- 
"
Please contact *[email protected]* with any questions
"

email <- compose_email(body = email_body,
                       footer = email_footer)

# preview e-mail in Viewer pane
preview_email(email)

 

Now that we’ve created the e-mail programmatically, the next step is to actually send it out. Because my company uses RStudio Connect to host reports and send e-mail notifications, I need to add the following two lines of code to the bottom of my report so that RStudio Connect knows what to use as the e-mail body:

# Use Blastula's message as the email body in RStudio Connect.
rmarkdown::output_metadata$set(rsc_email_body_html = email$html_str)
rmarkdown::output_metadata$set(rsc_email_images = email$images)

Before this point, the blastula code we’d written generated a nice HTML e-mail, which in this case had been saved to a variable I called email. However Connect didn’t know that. To remedy this, we saved the e-mail we created to the output_metadata object. The output_metadata object contains “metadata”, or information, some of which Connect uses. Two of those items are rsc_email_body_html and rsc_email_images, which Connect uses to build the HTML notification e-mail it sends out. For consistency, you can always assign both of these items at the end of your R Markdown report, even if initially it does not contain embedded images.

Rather than use RStudio Connect, you can also use the smtp_send() function to send your e-mail via a SMTP server. For instructions, check out the package’s “Sending Email Using SMTP” vignette on github. To learn more about more about crafting custom e-mails, check out the blastula documentation and the RStudio Connect User Guide.

To leave a comment for the author, please follow the link and comment on their blog: R Views.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)