You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Azure VM中R用gmailr和gargle发邮件失败求助

问题:Azure Windows VM上R脚本的gmailr凭据获取失败

我之前在Windows Azure VM上运行R脚本推送运行状态通知,去年10月起功能失效。试过相关解决方案,仅成功两次后又出现相同错误。已确认凭据有效,求解决思路。

我的代码

library(gmailr)
library(tidyr)
library(gargle)

send_email_on_error  <- function(send = "abc@gmail.com"
                                 ,to="abc@gmail.com"
                                 ,subject
                                 ,body) {
  
  cred_funs_clear()
  
  cred_funs_add(credentials_user_oauth2 = credentials_user_oauth2)
  
  gm_auth_configure(path="path\\GmailKey.json")
                    
  # options(
  #    gargle_oauth_cache = "secret",
  #    gargle_oauth_email = "abc@gmail.com"
  #  )
  
  gm_auth(email = "abc@gmail.com")
  
  cred_funs_set_default()
  
  # Send an email
  email<- gm_mime() %>%
    gm_to(to) %>%
    gm_from(send) %>%
    gm_subject(subject) %>%
    gm_text_body(body)
  
  gm_send_message(email)
  
}

send_email_on_error(subject="test from vm",body= "test from vm")

print("done")

错误信息

trying `token_fetch()`
trying `credentials_user_oauth2()`
Gargle2.0 initialize
adding "userinfo.email" scope
Error caught by `token_fetch()`:
error reading from connection
Error in `gm_auth()`:
! Can't get Google credentials.

解决思路

  • 检查网络连接与防火墙:确认Azure VM的出站规则允许访问Google OAuth相关域名(如accounts.google.com),临时关闭VM防火墙测试是否恢复正常。
  • 清理并重置令牌缓存:删除gargle默认的OAuth缓存目录(.R/gargle),或者取消代码中options部分的注释,指定一个有读写权限的缓存路径,确保VM对该路径有访问权限。
  • 切换为服务账号认证:使用Google服务账号替代用户OAuth,下载服务账号的JSON密钥,修改认证代码为gm_auth(path = "service-account-key.json", scopes = "https://www.googleapis.com/auth/gmail.send"),同时在Gmail中给服务账号邮箱授予发送权限。
  • 更新依赖包:运行install.packages(c("gmailr", "gargle"))更新到最新版本,新版本可能修复了OAuth连接的兼容性问题。
  • 验证凭据文件路径:确认GmailKey.json的路径正确,Windows环境下使用双反斜杠\\或正斜杠/,避免路径包含空格或特殊字符,可通过file.exists("path\\GmailKey.json")测试路径有效性。
  • 启用调试模式定位问题:设置options(gargle_verbosity = "debug")后重新运行代码,查看详细的请求日志,找到连接失败的具体环节。

内容的提问来源于stack exchange,提问作者Phil C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:05:02