之前尝试了如下的几种linux 软件:
但无奈发现,都需要使用root 权限,而且配置稍显麻烦。
直到发现mailR
包。
需要安装jdk,官网下载或者使用conda,都可以:
$ java -version
openjdk version "11.0.15-internal" 2022-04-19
OpenJDK Runtime Environment (build 11.0.15-internal+0-adhoc..src)
OpenJDK 64-Bit Server VM (build 11.0.15-internal+0-adhoc..src, mixed mode)
相关R 包安装,conda 解决依赖:
mamba install -y r-rjava r-mailr
格式如下:
mailR::send.mail(
from = 'sender@tuandai.com', # 发送人
to = 'sendee@tuandai.com', # 接收人
cc = 'carboncopy@tuandai.com', # 抄送人
subject = '邮件标题',
body = as.character(
'<div style = "color:red">邮件正文,可以为HTML格式</div>'
),
attach.files = NULL, # 附件的路径
encoding = "utf-8",
smtp = list(
host.name = 'smtp.exmail.qq.com', # 邮件服务器IP地址
port = 465, # 邮件服务器端口
user.name = 'senderName', # 发送人名称
passwd = 'yourpassword', # 密码
ssl = T),
html = T, inline = T, authenticate = T, send = T, debug = F
)
比如我通过QQ 邮箱发送:
send.mail(from = "your mail",
to = "to mail",
subject = "Test",
body = "Hello, this mail is from R",
smtp = list(host.name = "smtp.exmail.qq.com", port = 465, user.name = "your mail", passwd = 'your passwd', ssl = TRUE),
authenticate = TRUE,
send = TRUE)
成功了:
涉及到密码的操作,在[[70-R茶话会15-你的编程菜鸟路上缺失的一课]],我们就提过,最好通过设置环境变量来访问他们:
Sys.setenv(
UID = "User ID",
PASS = 'PASSWD',
)
或者直接在一个脚本里赋值变量:
UID = ""
PASS = ''
直接在mailR 使用这些变量就好了:
source("~/script/set_environment.R")
mailR::send.mail(from = UID,
to = UID,
subject = "Test",
body = "Hello, this mail is from R",
smtp = list(host.name = "smtp.exmail.qq.com", port = 465, user.name = UID, passwd = PASS, ssl = TRUE),
authenticate = TRUE,
send = TRUE)
有了这个R脚本,我们就可以在shell 中对其调用,实现邮件提示的功能。
[1]
第 8 章 mailR | R语言模型部署实战 (dataxujing.github.io): https://dataxujing.github.io/R_online/mailr.html
[2]
R软件每日自动发送邮件(mailR包) - 简书 (jianshu.com): https://www.jianshu.com/p/493fcd24aab9