0
votes

I've went through the more or less similar questions here on StackOverflow. The closest that answers my question is this one Downloading attachment from Outlook into R

In Outlook, I've a custom folder named '47MY Daily Report', which contains daily reports with the same email title and each one of them would have a zip attachment.

There are probably more than hundreds of daily emails in that folder,and each has a zip attachment.

What I want to do is 1. Download all these zip attachments. 2. Unzip them 3. Rename the excel file that is contained in each zip attachment based on the received date time (daily_report_20190913-1530.xls) 4. save these excel files in one folder.

I'm still struggling at the first step, where I need to download all these zip files from each email.

Below is what I currently have

library(RDCOMOutlook)

# search emails and store as tibble
df_47MY <- RDCOMOutlook::search_emails(folder = 'Inbox', search_term = '47MY Daily Report')
# prepare filename for each attachment
df_47MY$filename <- paste(gsub(':','',gsub('-','',gsub(' ','_',gsub("GMT", "", df_47MY$received)))), '.xls',sep = '')

1

1 Answers

0
votes

I managed to find a solution using the RDCOMOutlook package. It provides a higher level function on top of RDMCOMClient.

library(RDCOMOutlook)

# look for all the emails with this title
df_47JB_KPI <- RDCOMOutlook::search_emails(folder = 'Inbox', search_term = '47JB Migration KPI Report')

# prepare filename for each attachment
df_47JB_KPI$filename <- paste(gsub(':','',gsub('-','',gsub(' ','_',gsub("GMT", "", df_47JB_KPI$received)))), '.xls',sep = '')

# function that download, unzip, and rename the attachment
download_unzip_rename <- function(x, y) {
  file.rename(unzip(RDCOMOutlook::save_attachments(x,target_dir = getwd())),y)
}


dfs <- df_47JB_KPI[1:nrow(df_47JB_KPI),]
# run function to download all attachments, rename them
for (i in seq_along(dfs$email)) {
  print(i)
  email <- dfs$email[[i]]
  filename <- dfs$filename[i]
  download_unzip_rename(email, filename)
}