代码之家  ›  专栏  ›  技术社区  ›  Jan

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

  •  0
  • Jan  · 技术社区  · 6 年前

    我想用R中的SMTPS发送邮件。目前,没有一个可用的包支持通过TLS发送邮件( rmail & sendmaileR )或者它们有一个难以安装的Java依赖关系( mailr

    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'
    

    不幸的是,我无法将这个片段翻译成R使用辉煌 curl 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 回复  |  直到 6 年前
    推荐文章