通过迭代保存从电子邮件中提取的附件

时间:2019-04-03 03:18:47

标签: r loops email outlook

我能够识别并提取我需要的所有必要电子邮件。我还将每个电子邮件的附件保存到另一个变量。但是,我在将这些附件保存到本地文件夹时遇到了问题,特别是那些文件类型= .xlsx的附件。

library(RDCOMClient)
setwd("C:/Updated")
outlook_app <- COMCreate("Outlook.Application")
search <- outlook_app$AdvancedSearch(
  "Inbox",
  "urn:schemas:httpmail:subject like '%Daily Efficiency Tracker%'"
)

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

attachment_file <- getwd()

for (i in 1:results$Count()) {
  if (as.Date("1899-12-30") + floor(results$Item(i)$ReceivedTime()) 
      == as.Date("2019-04-02")) {
    email <- results$Item(i)
    attachment <- email$Attachments()
    for(j in 1:attachment$Count()){
      if (grepl(".xlsx", attachment$Item(i)$FileName(), ignore.case = TRUE)) {
        attachment$Item(i)$SaveAsFile(attachment_file)
      }
    }
  }
}

当我逐行运行它时,我在这部分上只有错误:

attachment$Item(i)$SaveAsFile(attachment_file)

下面是错误消息:

<checkErrorInfo> 80020009 
No support for InterfaceSupportsErrorInfo
checkErrorInfo -2147352567
Error: Exception occurred.

2 个答案:

答案 0 :(得分:0)

我已经设法执行以下操作,但是如果您收到一条消息,但没有要查找的指定文件附件,则会导致错误。

library(RDCOMClient)
library(openxlsx)

setwd("C:/Users/JGGliban/Desktop/Work/ADMIN/Data Integrity/DI OT Tracker")
outlook_app <- COMCreate("Outlook.Application")
search <- outlook_app$AdvancedSearch(
  "Inbox",
  "urn:schemas:httpmail:subject like '%Daily Efficiency and OT Tracker%'"
)

Sys.sleep(10)
results <- search$Results()
attachment_file <- tempfile()

date <- function(){
  if ((wday(format(Sys.Date(), "%Y-%m-%d"), label = FALSE)) == 1){
    return(format(Sys.Date()-3, "%Y-%m-%d"))
  } else {
    return(format(Sys.Date()-1, "%Y-%m-%d"))
  }
}

for (i in 1:results$Count()) {
  if (as.Date("1899-12-30") + floor(results$Item(i)$ReceivedTime()) == as.Date(date())) {
    email <- results$Item(i)
    attachment <- email$Attachments()

    for(j in 1:attachment$Count()) {
      if (grepl(".xlsx", attachment$Item(j)$FileName(), ignore.case = TRUE)) {
        attachmentname <- attachment$Item(j)$FileName()
        attachment_file <- paste0(getwd(), "/", attachmentname)
        attachment$Item(j)$SaveAsFile(attachment_file)
      }
      Sys.sleep(10)
    }
  }
}

答案 1 :(得分:0)

Windows在R中使用“反斜杠”而不是“正斜杠”。因此,当您提供要保存附件的文件路径时,需要将“正斜杠”更改为“双反斜杠”。

使用gsub的示例:

attachment_file<-paste0(gsub("/","**\\\\\\\\**",getwd()), "\\\\", attachmentname)