Exposing the Gmail API from R.
Get the released version from CRAN:
Or the development version from github with:
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
test_email <- gm_mime() %>% gm_to("PUT_A_VALID_EMAIL_ADDRESS_THAT_YOU_CAN_CHECK_HERE") %>% gm_from("PUT_THE_GMAIL_ADDRESS_ASSOCIATED_WITH_YOUR_GOOGLE_ACCOUNT_HERE") %>% gm_subject("this is just a gmailr test") %>% gm_text_body("Can you hear me now?") # Verify it looks correct gm_create_draft(test_email) # If all is good with your draft, then you can send it gm_send_message(test_email)
You can add a file attachment to your message with
# 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)[]) # The messages in the thread will now be in a list latest_thread$messages # Retrieve parts of a specific message with the accessors my_msg <- latest_thread$messages[] gm_to(my_msg) gm_from(my_msg) gm_date(my_msg) gm_subject(my_msg) gm_body(my_msg) # If a message has attachments, download them all locally with `gm_save_attachments()`. gm_save_attachments(my_msg)
my_drafts = gm_drafts()
my_history = history(start_num)
my_labels = gm_labels()
my_messages = gm_messages("search query")
my_threads = gm_threads("search query")
modify_thread(thread_id, add_labels=c("label_1"), remove_labels=c("label_2"))
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.
Enable the Gmail APIbutton.
DOWNLOAD CLIENT CONFIGURATIONon your computer.
GMAILR_APPenvironment variable to the location of the JSON file, it is convienent to do this in your
usethis::edit_r_environ(). Then calling
gm_auth_configure()with no arguments.
gm_auth()to start the OAuth flow to verify to google that you would like your gmailr project to have access to your email. You will get a scary warning about an untrusted application, this is because the application is the one you just created, click advanced and
Go to gmailrto proceed to do the oauth flow.
gm_auth(). You can see a full list of available scopes from
Only very heavy usage of the Gmail API requires payment, so use of the API for most people should be free.
If you are using gmailr in a deployed application you will need to copy two pieces to your deployed location.
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.
credentials.json and the
.secret directory to your remote location.
# 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.