Easily Send HTML Email Messages

Compose and send out responsive HTML email messages that render perfectly across a range of email clients and device sizes. Messages are composed using 'Markdown' and a text interpolation system that allows for the injection of evaluated R code within the message body, footer, and subject line. Helper functions let the user insert embedded images, web link buttons, and 'ggplot2' plot objects into the message body. Messages can be sent through an 'SMTP' server or through the 'Mailgun' API service < http://mailgun.com/>.

Travis-CI Build Status codecov.io

Sometimes we need to send out email messages based on the results of automated analysis processes. For these such instances, let's endeavor to send out some pretty-nice-looking HTML email messages. The blastula package makes it easy to send out HTML emails that are a little bit easier on the eyes. As an added bonus we can take advantage of both markdown and R code when composing our email text. The best way to demonstrate this is to just show an example workflow...

Here's an example that shows a basic workflow for composing the message, previewing the content, creating optional on-disk credentials for email, and sending out the message.

There are 4 main functions in this package:

  • compose_email(): generates the email message content inside the email_message-class object
  • preview_email(): makes the email message created by compose_email() viewable in the RStudio Viewer
  • send_email_out(): sends the HTML-based email to one or more recipients
  • create_email_creds_file(): generates an optional on-disk, serialized file with email credentials

Some helper functions allow for easy injection of objects in the message body. These are:

  • add_cta_button(): add a call-to-action (CTA) button with button text and a link
  • add_image(): with a local image file, insert it into message
  • add_ggplot(): add a ggplot plot object as an inline image

When you compose an email, you can use character objects in the global workspace and splice those into the message content. Here, I'll create a nicely formatted date/time string (current_date_time), and, assign a link to an web image to an object (img_link).

# Get a nicely formatted date/time string
current_date_time <-
    format(Sys.time(), "%A, %B "),
    format(Sys.time(), "%d") %>% as.numeric(),
    ", ",
    format(Sys.time(), "%Y"),
    " at ",
    format(Sys.time(), "%l:%M") %>% trimws(),
    toupper(format(Sys.time(), " %p")),
    format(Sys.time(), " (%Z)"))
# Assign a very long image URL to `img_link`
img_link <-

Now, we can use the compose_email() to compose the email! There are two main arguments here, body and footer. You can supply markdown text to each of these. So things like ##, links, tables, and all other valid markdown conventions should render to valid HTML.

Furthermore, string interpolation is possible and it works by enclosing valid R code inside of curly braces ({...}). Below the image URL (as part of the ![...](...) markdown link contruction) is referenced to the img_link object from the global workspace. Note also that {current_date_time} references a character object that took quite a few piped statements of R to generate. The end result is the date/time string being nicely inserted in the footer of the email without complicating the compose_email() function call itself with lots of R statements.

We can also supply variables in the compose_email() function directly. For example, the {sender} part references an object not in the global workspace but rather it refers the named argument sender = "Mike" in the function call. (The order of searching is from within the function first, then the search moves to variables in the global environment.)

email_object <-
    body = "
  ## Hiya! This is an email message. Exciting Right?
  Enjoy it. And this here image:
  ![The alt text]({img_link} \"The title\")
  **Yeah!** I seriously hope that you enjoy this \\
  message and the good vibes it will bring to you \\
  and yours.
  Peace out,
    footer = 
  "Brought to you by Smile AG on {current_date_time}",
    sender = "Mike")

Some more notes on style are useful here. The \\ is a helpful line continuation marker. It'll help you break long lines up when composing but won't introduce line breaks or new paragraphs. I recommend formatting like above with few indents so as not to induce the quote-type formatting. Any literal quotation marks should be escaped using a single \. Blank lines separating blocks of text result in new paragraphs. And, again, any valid R code can be enclosed inside {...} (e.g., {Sys.Date()}).

After creating the email message, you'll most certainly want to look at it to ensure that the formatting is what you want it to be. This is done with the preview_email() function. It's easy to use!

# Preview the email
preview_email(email = email_object)

...and this is what I saw:

Looks good. Time to email this. I'd previously set up my email credentials in a file using the create_email_creds_file() function. Here's an example of how one might create a creds file as a hidden file in the home directory (~).

# Create a credentials file to facilitate
# the sending of email messages
  file = "~/.e_creds",
  sender = "[email protected]",
  host = "smtp.blastula.org",
  port = 465,
  user = "[email protected]",
  password = "************")

Having generated that file, you can use the send_email_out() function to send the email. I sent the email just to myself but do note that the recipients argument can accept a vector of email addresses for mass mailings. If using a credentials file seems like not a very good practice, one can instead set a number of environment variables and use Sys.getenv() calls for email credentials arguments in the send_email_out() statement.

# Sending email using a credentials file
  message = email_object,
  from = "[email protected]",
  recipients = "[email protected]",
  subject = "This is NOT junk mail.",
  creds_file = "~/.e_creds")
# Sending email using environment variables
  message = email_object,
  from = "[email protected]",
  recipients = "[email protected]",
  subject = "This is NOT junk mail.",
  sender = Sys.getenv("bls_sender"),
  host = Sys.getenv("bls_host"),
  port = Sys.getenv("bls_host"),
  user = Sys.getenv("bls_username"),
  password = Sys.getenv("bls_password"))

Oddly enough, when I checked my email client, this message did appear in my Junk Mail folder. I fished it out, and this is how it appeared:

Which is great. The underlying HTML/CSS is meant to be resilient and display properly across a wide range of email clients and webmail services.

Adding a table to an email message

You can add HTML tables to the message. Here's an example using a formattable table generated via its format_table() function.

# Create a data frame
df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  stringsAsFactors = FALSE)
# Create an HTML table with `format_table()`
formatted_table <-
    x = df,
      age = color_tile("white", "orange"),
      grade = 
          style = x ~ ifelse(
            x == "A", 
            style(color = "green", font.weight = "bold"), NA)), 
      area(col = c(test1_score, test2_score)) ~ normalize_bar("pink", 0.2),
      final_score = 
          style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
          x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
      registered = 
          style = x ~ style(color = ifelse(x, "green", "red")),
          x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
# Create and preview the email message
  body = "
  Here are the grades you've been hounding me \\
  for all this past week. Overall, everyone did \\
  quite well. I'm impressed.
  <br />
  Cheers,<br />The grader") %>%

This is how the email preview appears:

Bear in mind that wider tables are less responsive than text with smaller viewport widths, so, previewing the message is vital (along with recognizing whether recipients will be primarily viewing on mobile or desktop).

Adding a call-to-action (CTA) button to an email message

You can add a CTA button to the message. Simply use the add_cta_button() helper function, which generates an HTML fragment that can be injected into the message. The function can be called either in the global environment (referencing the object cta_button inside {...} as below) called within the email message body itself (which is less recommended due to readability considerations).

# Create a CTA button as an
# HTML fragment to be included
# in the message
cta_button <-
    url = "http://www.thebestwebsite.com",
    text = "Press This Button",
    align = "center")
# Compose the email and include the
# `cta_button` HTML fragment in a
# single line
  body = "
  Below is a call. It's a call to \\
  action. Press it!
  (I really hope you press it.)
  ") %>%

This is how the email preview appears:

Adding a local image to an email message

It's really a cinch to include images hosted on the Web using the Markdown approach shown earlier. But, what about local image files you have on your comp? Well that's easy too! Use the add_image() helper function and you'll get an HTML fragment that can be placed into the message wherever you'd like the image to be. Again, this can function be used either in the global environment or within the email message body itself. I'll refer to an image that is available in the package.

# Create an HTML fragment that
# contains an image
img_file_path <-
    package = "blastula")
img_file_html <-
    file = img_file_path)
# Include the image in the email
# message body by simply referencing
# the `img_file_html` object
  body = "
  Take a look at this image:
  Funny, right?
  ") %>%

This is how the email preview appears:

I do think it's funny. And useful.

Adding a ggplot plot object to an email message

It's not at all difficult to insert a ggplot plot into an email message. The function to use for that is add_ggplot(). An example:

# Create a ggplot plot object
plot <- 
    data = mtcars,
      x = disp, y = hp,
      color = wt, size = mpg)) +
# Let's use the `add_ggplot()`
# helper function right inside the
# email message body this time
  body = "
  Take a look at this plot:
  {add_ggplot(plot_object = plot, width = 7, height = 5)}
  It's a nice plot.
  ") %>%

This is how the email preview appears:

Adding HTML tags with inline CSS

You can add custom HTML within the markdown text. This provides an opportunity to style the text using inline CSS. In this example, header text is centered with the text-align style and link text is rendered in the code style using <code> tags.

# Center the header text with some HTML tags, and,
# use the <code> tag for a link
  body = "
  <h2 style=\"text-align:center;\">This Heading is Centered</h2>
  That worked because we can insert HTML tags and \\
  include inline CSS. Check out this webpage for \\
  more information on this topic:
  <code>[CSS Align](https://www.w3schools.com/css/css_align.asp)</code>
  ") %>%

This is how the email preview appears:

Installation of the package

blastula is used in an R environment. If you don't have an R installation, it can be obtained from the Comprehensive R Archive Network (CRAN).

You can install the development version of blastula from GitHub using the devtools package.


If you encounter a bug, have usage questions, or want to share ideas to make this package better, feel free to file an issue at github.


blastula 0.1

  • Added functions to compose (compose_email()), preview (preview_email()), and send (send_email_out() and send_by_mailgun()) HTML email messages

  • Added helper functions for inserting HTML fragments into the message body (add_cta_button(), add_image(), and add_ggplot())

  • Added a function to help generate a secret credentials file for sending email through SMTP

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.


0.2.1 by Richard Iannone, 2 days ago


Report a bug at https://github.com/rich-iannone/blastula/issues

Browse source code at https://github.com/cran/blastula

Authors: Richard Iannone [aut, cre] (<https://orcid.org/0000-0003-3925-190X>)

Documentation:   PDF Manual  

MIT + file LICENSE license

Imports commonmark, downloader, dplyr, ggplot2, glue, htmltools, httr, magrittr, stringr, tidyr

Suggests covr, testthat

See at CRAN