Azure pipelines build status Azure pipelines test status Azure pipelines coverage status Build Status

Exposing the Gmail API from R.


Get the released version from CRAN:


Or the development version from github with:

# install.packages("devtools")

Writing new emails

Create a new email with gm_mime() and the helper functions. When testing it is recommended to use gm_create_draft() to verify your email is formatted as you expect before automating it (if desired) with gm_send_message().

test_email <-
  gm_mime() %>%
  gm_subject("this is just a gmailr test") %>%
  gm_text_body("Can you hear me now?")

# Verify it looks correct

# If all is good with your draft, then you can send it

You can add a file attachment to your message with gm_attach_file().

write.csv("mtcars.csv", mtcars)
test_email <- gm_attach_file("mtcars.csv")

# Verify it looks correct

# If so, send it

Reading emails

gmail shows you threads of messages in the web UI, you can retrieve all threads with gm_threads(), and retrieve a specific thread with gm_thread()

# view the latest thread
my_threads <- gm_threads(num_results = 10)

# retrieve the latest thread by retrieving the first ID

latest_thread <- gm_thread(gm_id(my_threads)[[1]])

# The messages in the thread will now be in a list

# Retrieve parts of a specific message with the accessors
my_msg <- latest_thread$messages[[1]]


# If a message has attachments, download them all locally with `gm_save_attachments()`.



In order to use gmailr you will need to create a google project for it. The easiest way to do this is via the Python Quickstart.

Only very heavy usage of the Gmail API requires payment, so use of the API for most people should be free.

Using gmailr in deployed applications

If you are using gmailr in a deployed application you will need to copy two pieces to your deployed location.

  1. The application JSON file, that you setup in the local setup.
  2. The oauth token cache, by default this is ~/.R/gargle/gargle-oauth

The easiest thing to do to ensure you are copying only the gmailr oauth token is to set this explicitly locally, e.g. do the following.

Run locally

# Configure your app
gm_auth_configure(path = "credentials.json")

# Authenticate with the new cache, store tokens in .secret
gm_auth(cache = ".secret")
# Go through the oauth flow

Then copy credentials.json and the .secret directory to your remote location.

Run remotely

# Configure your app
gm_auth_configure(path = "credentials.json")

# Authenticate with the tokens in the copied cache
gm_auth(email = TRUE, cache = ".secret")

There are additional details on dealing with non-interactive auth in the gargle documentation.


Privacy policy

Community Examples

Try the gmailr package in your browser

Any scripts or data that you put into this service are public.

gmailr documentation built on Aug. 23, 2019, 5:06 p.m.