Extract Zip + CSV file from attachment w / Image in message body

I get daily emails where there is an attachment containing 1 zip file containing 1 csv file.

There is an image in the body of my email that is recognized as another attachment. I'm sure.

enter image description here

The below script works when there is only text in the body of the email but with the "Adobe Marketing Cloud" image, it spins the script.

Is there a way that I can only read, perhaps the first attachment is being read (assuming it will be a zip file)?

Here's my script:

library(readr)
library(RDCOMClient)
outlook_app <- COMCreate("Outlook.Application")
search <- outlook_app$AdvancedSearch(
  "Inbox",
  "urn:schemas:httpmail:subject = 'SUBJECTNAME'"
)

Sys.sleep(5) # Wait a hot sec!


results <- search$Results() # Saves search results into results object

Sys.sleep(5) # Wait a hot sec!

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

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

# Iterates through results object to pull out all of the items
for (i in 1:results$Count()) {
  if (as.Date("1899-12-30") + floor(results$Item(i)$ReceivedTime()) 
      == as.Date(Sys.Date())) {
    email <- results$Item(i)
  }
}

attachment_file <- tempfile()
email$Attachments(1)$SaveAsFile(attachment_file)

##Automatically Determine csv file name
file_name<-unzip(attachment_file,list=TRUE)
csv_file<-file_name$Name

##Read CSV File
newly_read_data <- read_csv(unz(attachment_file,csv_file))

      

The error is here:

file_name<-unzip(attachment_file,list=TRUE)
Error in unzip(attachment_file, list = TRUE) : 
  zip file 'C:\Temp\Rtmp86Gnzp\file29904a23387b' cannot be opened

      

Any help would be great, thanks!

+2


source to share


1 answer


email$Attachments(1)$SaveAsFile(attachment_file)

will save the first attachment to a file path specified attachment_file

in an unknown order. If you are sure that there will only be one ".zip" file, you can use the method FileName

to check that the attachment name contains ".zip":



attachment_file <- tempfile()

for (i in 1:email$Attachments()$Count()) {
    attachment <- email$Attachments(i)
    if (grepl(".zip", attachment$FileName(), ignore.case = TRUE)) {
        attachment$SaveAsFile(attachment_file)
    }
}

      

+1


source







All Articles