Search code examples
rdockergoogle-cloud-platformgmailr

Why is gmailr not working in docker build process?


I'm using the gmailr package for sending emails from a r script.

Locally it's all working fine, but when I try to run this during a docker build step in google cloud I'm getting an error.

I implemented it in the following way described here. So basically, locally the part of my code for sending emails looks like this:

gm_auth_configure(path  = "credentials.json")
gm_auth(email = TRUE, cache = "secret")
gm_send_message(buy_email)

Please note, that I renamed the .secret folder to secret, because I want to deploy my script with docker in gcloud and didn't want to get any unexpected errors due to the dot in the folder name.

This is the code, which I'm now trying to run in the cloud:

setwd("/home/rstudio/")
gm_auth_configure(path  = "credentials.json")
options(
  gargle_oauth_cache = "secret",
  gargle_oauth_email = "[email protected]"
)
gm_auth(email = "[email protected]")

When running this code in a docker build process, I'm receiving the following error:

Error in gmailr_POST(c("messages", "send"), user_id, class = "gmail_message",  : 
  Gmail API error: 403
  Request had insufficient authentication scopes.
Calls: gm_send_message -> gmailr_POST -> gmailr_query

I can reproduce the error locally, when I do not check the following box.

Therefore my first assumption is, that the secret folder is not beeing pushed correctly in the docker build process and that the authentication tries to authenticate again, but in a non interactive-session the box can't be checked and the error is thrown. This is the part of the Dockerfile.txt, where I'm pushing the files and running the script:

#2 ADD FILES TO LOCAL
COPY . /home/rstudio/

WORKDIR /home/rstudio

#3 RUN R SCRIPT
CMD Rscript /home/rstudio/run_script.R

and this is the folder, which contains all files / folders beeing pushed to the cloud.

My second assumption is, that I have to somehow specify the scope to use google platform for my docker image, but unfortunately I'm no sure where to do that.

I'd really appreciate any help! Thanks in advance!


Solution

  • For anyone experiencing the same problem, I was finally able to find a solution.

    The problem is that GCE auth is set by the "gargle" package, instead of using the "normal user OAuth flow".

    To temporarily disable GCE auth, I'm using the following piece of code now:

    library(gargle)
    cred_funs_clear()
    
    cred_funs_add(credentials_user_oauth2 = credentials_user_oauth2)
    
    gm_auth_configure(path  = "credentials.json")
    options(
      gargle_oauth_cache = "secret",
      gargle_oauth_email = "[email protected]"
    )
    gm_auth(email = "email.which.was.used.for.credentials.com")
    
    cred_funs_set_default()
    

    For further references see also here.