不得不说这是一个很牛的R包,非常实用!mailR包依赖Java环境,所有需要提前在Window10电脑上安装Java,配置JAVA_HOME变量,然后安装rJava,再安装mailR。再执行下面的代码:
## 1.导入R包
library(mailR)
library(rJava)
## 2.获取附件文件的路径信息
# 获取当前日期信息
date <- Sys.Date()
# [1] "2020-11-20"
date_time <- format(Sys.time(),format="%Y-%m-%d %H")
# [1] "2020-11-20 14"
date_time2 <- format(Sys.time(),format="%Y-%m-%d")
# [1] "2020-11-20"
setwd("E:/使用R群发邮件")
file_path <- paste0("./测试数据/",format(Sys.time(),format="%Y"),"/",format(Sys.time(),format="%Y-%m-%d"),"/测试文件_",format(Sys.time(),format="%Y-%m-%d"), ".xlsx") #邮件要发送的附件地址
或者
file_path <- paste0("./",list.files(path = "./", pattern = "xlsx$"))
## 3.核心代码
mailR::send.mail(from = 'xxx@163.com', # 发送人
to = c('xxx@163.com', 'xxx@foxmail.com'), # 接收人 , 'saracar@163.com'
cc = 'xxx@yeah.net', # 抄送人
subject = paste0("测试数据_",date_time2), #邮件题目
body = as.character('<div style = "color:red">这是使用R发送的测试邮件,请查收附件中的测试数据!</div>'), #邮件正文
attach.files = c(file_path), # 附件的路径
encoding = "utf-8",
smtp = list(host.name = 'smtp.163.com', # 邮件服务器IP地址
port = 25, # 邮件服务器端口
user.name = 'xxx@163.com', # 发送人名称
passwd = "XXXXXXXXXXXXXX", # 163邮箱授权码
ssl = T),
html = T, inline = T, authenticate = T, send = T, debug = F)
# 成功发送邮件显示:
# [1] "Java-Object{org.apache.commons.mail.ImageHtmlEmail@5891e32e}"
## 4.收尾
sessionInfo()
# R version 3.6.3 (2020-02-29)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 10 x64 (build 18363)
#
# Matrix products: default
#
# locale:
# [1] LC_COLLATE=Chinese (Simplified)_China.936
# [2] LC_CTYPE=Chinese (Simplified)_China.936
# [3] LC_MONETARY=Chinese (Simplified)_China.936
# [4] LC_NUMERIC=C
# [5] LC_TIME=Chinese (Simplified)_China.936
#
# attached base packages:
# [1] grid stats graphics grDevices utils datasets methods
# [8] base
#
# other attached packages:
# [1] dplyr_1.0.2 ComplexHeatmap_2.0.0 praise_1.0.0
# [4] progress_1.2.2 argparse_2.0.3 corrplot_0.84
# [7] ggrepel_0.8.2 readxl_1.3.1 openxlsx_4.2.3
# [10] plotrix_3.7-8 ggplot2_3.3.2 rJava_0.9-12
# [13] mailR_0.4.1
#
# loaded via a namespace (and not attached):
# [1] shape_1.4.5 circlize_0.4.11 GetoptLong_1.0.4
# [4] tidyselect_1.1.0 xfun_0.19 purrr_0.3.4
# [7] colorspace_2.0-0 vctrs_0.3.5 generics_0.1.0
# [10] htmltools_0.5.0 yaml_2.2.1 rlang_0.4.8
# [13] R.oo_1.24.0 pillar_1.4.6 glue_1.4.2
# [16] withr_2.3.0 R.utils_2.10.1 RColorBrewer_1.1-2
# [19] lifecycle_0.2.0 stringr_1.4.0 munsell_0.5.0
# [22] gtable_0.3.0 cellranger_1.1.0 R.methodsS3_1.8.1
# [25] zip_2.1.1 GlobalOptions_0.1.2 evaluate_0.14
# [28] labeling_0.4.2 knitr_1.30 parallel_3.6.3
# [31] Rcpp_1.0.5 scales_1.1.1 jsonlite_1.7.1
# [34] farver_2.0.3 rjson_0.2.20 hms_0.5.3
# [37] png_0.1-7 digest_0.6.27 stringi_1.5.3
# [40] clue_0.3-57 tools_3.6.3 magrittr_2.0.1
# [43] tibble_3.0.4 cluster_2.1.0 crayon_1.3.4
# [46] pkgconfig_2.0.3 ellipsis_0.3.1 prettyunits_1.1.1
# [49] rmarkdown_2.5 rstudioapi_0.13 R6_2.5.0
# [52] compiler_3.6.3