如何使用R中的curl包通过SMTPS发送邮件?

时间:2019-03-09 21:09:59

标签: r email curl libcurl smtps

我想在R中使用SMTPS发送邮件。目前,没有可用的软件包支持通过TLS(rmailsendmaileR)发送邮件,或者它们很难安装Java依赖项( mailr)。我尝试使用curl并使用以下代码段成功发送了邮件:

curl --url 'smtps://mail.server.com:465' --ssl-reqd --mail-from 'mail1@example.com' --mail-rcpt 'mail2@example.com' --upload-file mail.txt --user 'user:password'

不幸的是,我无法使用出色的curl程序包将该代码段转换为R。当我设法找到所有选项时,curl语句每次都会使R会话崩溃。此外,我无法将mail.txt文件添加到在临时目录中创建的请求中。是否有人使用curl包管理邮件发送?为什么程序总是崩溃?目标应该是在所有平台上发送邮件。

# input variables
to <- "mail1@example.com"
from <- Sys.getenv("MAIL_USER")
password <- Sys.getenv("MAIL_PASSWORD")
server <- Sys.getenv("MAIL_SERVER")
port <- 465
subject <- "Test Mail"
message <- c("Hi there!",
             "This is a test message.",
             "Cheers!")

# compose email body
header <- c(paste0('From: "', from, '" <', from, '>'),
            paste0('To: "', to, '" <', to, '>'),
            paste0('Subject: ', subject))
body <- c(header, "", message)

# create tmp file to save mail text
mail_file <- tempfile(pattern = "mail_", fileext = ".txt")
file_con <- file(mail_file)
writeLines(body, file_con)
close(file_con)

# define curl options
handle <- curl::new_handle()
curl::handle_setopt(handle = handle,
                    mail_from = from,
                    mail_rcpt = to,
                    use_ssl = TRUE,
                    port = port,
                    userpwd = paste(from, password, sep = ":"))
con <- curl::curl(url = server, handle = handle)
open(con, "r")
close(con)

# delete file
unlink(mail_file)

0 个答案:

没有答案