Download attachment from an outlook email using R

前端 未结 1 2035
借酒劲吻你
借酒劲吻你 2020-12-04 23:25

I receive an email every Sunday with an attachment (a zipped folder). The subject of the email never changes. I want to find the latest email with the specified subject line

相关标签:
1条回答
  • 2020-12-04 23:46

    You can search your inbox, or any other folder, using the AdvancedSearch method:

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

    This is an asynchronous method, so R won't wait for the search to complete before moving on to the next step. While there does exist an AdvancedSearchComplete event to handle this, I haven't been able to work out how to do this with RDCOMClient. As a workaround, a Sys.sleep(5) should give the search enough time to complete.

    You can look through these results and query their received times with the ReceivedTime method. To convert these times to dates, use the Microsoft Office base date of December 30, 1899:

    results <- search$Results()
    results$Item(1)$ReceivedTime() # Received time of first search result
    as.Date("1899-12-30") + floor(results$Item(1)$ReceivedTime()) # Received date
    

    We can now look through the results for an email received on a particular date, say August 14, 2017.

    for (i in 1:results$Count()) {
        if (as.Date("1899-12-30") + floor(results$Item(i)$ReceivedTime()) 
                == as.Date("2017-08-14")) {
            email <- results$Item(i)
        }
    }
    

    We can look through the attachments of an email similar to how we looked through search results. The first attachment will be email$Attachments(1) (watch out for pictures in email signatures; these will also show up!). If you're interested in a particular attachment, you can find it with the FileName method. Once you've found the attachment you want, you can save it to a file and begin to use it as if it were any other file.

    attachment_file <- tempfile()
    email$Attachments(1)$SaveAsFile(attachment_file)
    data <- read.csv(attachment_file)
    

    I've used a temporary file path here, but you could of course save the attachment to a permanent location.

    0 讨论(0)
提交回复
热议问题