首页 > 解决方案 > 使用 RDCOMClient 和 for 循环从 R 中为每封电子邮件附加一个电子表格?

问题描述

几天前我在这个链接上问了这个问题。该解决方案部分有效,但问题是逻辑发送了大量带有所有附件的电子邮件,而不是每封电子邮件一个附件。下面是我的代码/逻辑。理想情况下,我希望每个附件发送一封电子邮件

#Create vector of all sheetname that are in my excel paths 
sheet_names <-  paste0(sheet_names_pre$Vendor_Name, ".xlsx")

#Sample of sheet_names
 [1] "60036819-SO PALMER DONOVAN.xlsx"       "60080204-SO BEACON SUPPLY.      .xlsx" "60009795-SO SRS DISTRIBUTION    .xlsx"
 [4] "60808049-SO GUARDIAN BLDG PROD.xlsx"   "60003551-SO OWENS CORNING SALES,.xlsx" "60292531-SO GAF BUILDING MATER..xlsx" 
 [7] "60004526-MERCHANTS METALS.xlsx"        "60360196-SO HENRY CO.xlsx"             "60660525-SO SIMPSON NO STRONG WL.xlsx"


#Directory name    
path_names <- "C:/Users/santi/Documents/"

#Concatenate directory and path 
attachments <-  c(paste0(path_names, sheet_names))

#Sample of attachments variable 
 [1] "C:/Users/santi/Documents/60036819-SO PALMER DONOVAN.xlsx"       "C:/Users/santi/Documents/60080204-SO BEACON SUPPLY.      .xlsx"
 [3] "C:/Users/santi/Documents/60009795-SO SRS DISTRIBUTION    .xlsx" "C:/Users/santi/Documents/60808049-SO GUARDIAN BLDG PROD.xlsx" 

#Logic to send out email
for(sheet in sheet_names) {
  #Concatenated and full path name       
  attachments = c(paste0(path_names, sheet_names))
  
  OutApp <- COMCreate("Outlook.Application")
  outMail = OutApp$CreateItem(0)
  outMail[["To"]] = paste("john_doe@outlook.com"
                          , sep=";", collapse=NULL)
  outMail[["subject"]] = " Open Quotes"
  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()
  
}

这里的问题可视化是正在发生的事情,它附加了所有电子邮件,而不是每个电子表格一封电子邮件:

在此处输入图像描述

标签: rloopsfor-loopxlsrdcomclient

解决方案


推荐阅读