Ubuntu环境下使用R的keyring库发送邮件失败求助
Ubuntu命令行执行R邮件脚本报错及crontab自动执行解决方案
问题背景
编写的R邮件脚本在Windows的R Studio中可正常运行,但在Ubuntu命令行执行时报错,需求是通过crontab实现每日自动发送邮件。
R脚本代码
library(keyring) library(blastula) keyring_unlock(password = "xx") create_smtp_creds_key( id = "gmailKonkurencja2", user = "xx111@gmail.com", host = "smtp.gmail.com", port = 465, provider = "gmail" ) email2 <- compose_email(body = "Test") email2 %>% smtp_send(to = "xx@xx", from = "xx@gmail.com", subject = "Test", credentials = creds_key("gmailKonkurencja2") )
报错信息
The system key store has been updated with the "blastula-v1-gmailKonkurencja2" key with the `id` value "gmailKonkurencja2". * Use the `view_credential_keys()` function to see all available keys * You can use this key within `smtp_send()` with `credentials = creds_key("gmailKonkurencja2")` Error in handle_setopt(h, ...) : Unknown option: login_options Calls: %>% ... smtp_send -> <Anonymous> -> new_handle -> handle_setopt
解决方案
1. 更新依赖包解决参数不兼容问题
这个错误是因为curl包版本过低,不支持login_options参数,blastula依赖该包实现邮件发送:
- 执行R命令更新相关包:
install.packages(c("curl", "blastula", "keyring"))
2. 适配Ubuntu命令行的密钥环配置
Ubuntu命令行环境下keyring无法像图形界面那样自动解锁,直接用原脚本在crontab中执行会失败,有两种适配方案:
方案一:使用明文凭据(简单直接,适合私有环境)
跳过keyring,直接用creds_plain()传入Gmail应用专用密码(需开启Gmail两步验证后创建):
library(blastula) email2 <- compose_email(body = "Test") email2 %>% smtp_send( to = "xx@xx", from = "xx111@gmail.com", subject = "Test", credentials = creds_plain( user = "xx111@gmail.com", password = "你的Gmail应用专用密码", host = "smtp.gmail.com", port = 465 ) )
方案二:配置密钥环自动解锁(更安全)
- 创建存储密钥环密码的文件,设置严格权限:
echo "你的密钥环密码" > ~/.keyring_pass chmod 600 ~/.keyring_pass - 修改脚本中的解锁逻辑:
library(keyring) library(blastula) # 从文件读取密码解锁密钥环 keyring_unlock(password = readLines("~/.keyring_pass")) # 后续邮件发送代码不变 email2 <- compose_email(body = "Test") email2 %>% smtp_send(to = "xx@xx", from = "xx@gmail.com", subject = "Test", credentials = creds_key("gmailKonkurencja2")) - crontab任务中添加环境变量,确保密钥环可用:
编辑crontab任务:
添加每日执行的任务(示例为每日9点):crontab -e0 9 * * * DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus Rscript /path/to/your/script.R >> /var/log/email_script.log 2>&1
3. 验证执行
- 先在命令行手动执行脚本,确认无报错:
Rscript /path/to/your/script.R - 查看日志文件确认crontab执行状态:
cat /var/log/email_script.log
内容的提问来源于stack exchange,提问作者Jan Jankowski Janek
相关产品推荐
相关产品推荐

