首页 > 解决方案 > 使用 For 循环从 R 发送电子邮件?使用 RDCOMClient

问题描述

我目前有 5 个电子表格,我需要将它们分别发送到 5 封电子邮件中。

这是我目前对电子邮件的逻辑:

#Script to send out
attachments <- c('C:/Users/santi/Documents/Cost Changes xlsx/spreadsheet.xlsx') #spreadsheet variable
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = paste("john_doe@outlook.com"
                        , sep=";", collapse=NULL)
outMail[["subject"]] = " Rebate"
outMail[["body"]] = "Hi - 

Attached is the spreadsheet

Let me know if you have any questions, thanks.

This is an automated message from RStudio please respond if you find any errors.

"
purrr::map(attachments, ~ outMail[["attachments"]]$Add(.))
outMail$Send()

我将如何迭代它以发送 5 封单独的电子邮件,同时附加相关的电子表格?

标签: rfor-loopemailautomationrdcomclient

解决方案


你还没有描述你的电子表格命名。

SheetNames <- c("sheet1.xls", "sheet2.xls", "sheet3.xls")
PathName <- "C:/Users/santi/Documents/Cost Changes xlsx/"

for (sheet in SheetNames) {

attachments = c(paste0(PathName, sheet))

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = paste("john_doe@outlook.com"
                        , sep=";", collapse=NULL)
outMail[["subject"]] = " Rebate"
outMail[["body"]] = "Hi - 

Attached is the spreadsheet

Let me know if you have any questions, thanks.

This is an automated message from RStudio please respond if you find any errors.

"
purrr::map(attachments, ~ outMail[["attachments"]]$Add(.))
outMail$Send()

}

推荐阅读