问题
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