使用R从Outlook中的邮件下载多个附件

5vf7fwbs  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(129)

如何使用R从Outlook下载多个附件(都是CSV)?
我的代码只是阅读第一个附件。我无法迭代邮件中存在的所有附件。
使用RDCOMClient作为库

library(RDCOMClient)

outlook_app <- COMCreate("Outlook.Application")

search <- outlook_app$AdvancedSearch(
  "Inbox",
  "urn:schemas:httpmail:subject = 'test'"
)

Sys.sleep(5)
results <- search$Results()

Sys.sleep(10)

results$Item(1)$ReceivedTime() # Received time of first search result

as.Date("1899-12-30") + floor(results$Item(1)$ReceivedTime()) # Received date

for (i in 1:results$Count()) {
  print(i)
  if (as.Date("1899-12-30") + floor(results$Item(i)$ReceivedTime())  == as.Date("2019-04-03")) {
      email <- results$Item(i)
  }
}

attachment_file <- tempfile()

email$Attachments(1)$SaveAsFile(attachment_file)

data <- read.csv(attachment_file)

无法保存第一个附件以外的附件。

bpzcxfmw

bpzcxfmw1#

我已经能够提取多个附加文件与以下代码:

library(RDCOMClient)
OutApp <- COMCreate("Outlook.Application")
outlookNameSpace <- OutApp$GetNameSpace("MAPI")

dir_Attached_Files <- "D:\\"
setwd(dir_Attached_Files)
msg_Files <- list.files()
nb_Files <- length(msg_Files)

list_Attached_Files <- list()
destination_dir <- "D:\\"

for(j in 1 : nb_Files)
{
  path_msg <- paste0(dir_Attached_Files, msg_Files[j])
  message <- outlookNameSpace$OpenSharedItem(path_msg)
  nb_Attached_Files <- message$Attachments()$Count()
  
  for(i in 1 : nb_Attached_Files)
  {
    print(i)
    attachment_file <- paste0(destination_dir, message$Attachments(i)$Filename())
    message$Attachments(i)$SaveAsFile(attachment_file)
    Sys.sleep(3)
  }
}

相关问题