Download the app from Outlook email using R

I receive an email every Sunday with an attachment (zip folder). The subject line never changes. I want to search for the last email with the specified subject line and download the attachment. I am a new R user and so far I have found a way to print the body of an email based on the subject (from one of the other questions asked on stackoverflow How to get emails for incoming Outlook messages using R RDCOMClient? ). Ideally I want to search for an email with the specified item received on a given date and then download the attachment. Can someone please point me in the right direction. Any help would be appreciated. Thank.

+3


source to share


1 answer


You can search for your mailbox 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 will not wait for the search to complete before moving on to the next step. Although there is a way to handle this event AdvancedSearchComplete

, I have not been able to figure out how to do it using RDCOMClient. As a workaround, a Sys.sleep(5)

should give the search enough time to complete.

You can view these results and query the resulting data using the method ReceivedTime

. To convert these dates 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 view the results by email received on a specific 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 may view email attachments similar to how we viewed the search results. The first app will be email$Attachments(1)

(watch out for images in email signatures, they'll show up too!). If you are interested in a specific application, you can find it using the method FileName

. Once you've found the attachment you want, you can save it to a file and start using 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 can of course save the attachment to a permanent location.

+5


source







All Articles