Save attachments extracted from e-mail by iterating

六月ゝ 毕业季﹏ 提交于 2021-01-28 11:13:38

问题


I was able to identify and extract all necessary e-mails I need. I also saved the attachments per e-mail to another variable. However, I'm having issue saving these attachments to a local folder, specifically those that are of file type = .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)
      }
    }
  }
}

When I run it line by line, I only had error on this part:

attachment$Item(i)$SaveAsFile(attachment_file)

Below is the error message:

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

回答1:


I've managed to do the below however, it results to an error if you receive a message WITHOUT the specified file attachment you are looking for.

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)
    }
  }
}



回答2:


Windows uses "backward slash" instead of "forward slash" in R. So when you give the file path where you want to save the attachment, you need to change "forward slash" to "double backward slash".

Example using gsub:

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


来源:https://stackoverflow.com/questions/55486537/save-attachments-extracted-from-e-mail-by-iterating

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!