How to retrieve the body of an Outlook email in my inbox using R?

458 Views Asked by At

I regularly use the R package RDCOMClient to send emails straight from R, but is there a way to use it to import the body of emails in my inbox into R?

Ive seen some answers on here like from here... How to retrieve Outlook inbox emails using R RDCOMClient?

But none of these seem to work and they are rather old answers or there are errors when I run them.

I also can't find any tutorials or documentation on how to really use RDCOMClient in relation to Outlook emails. Any help would be appreciated

2

There are 2 best solutions below

4
Emmanuel Hamel On BEST ANSWER

Here is one approach that can be considered :

library(RDCOMClient)

## create outlook object
OutApp <- COMCreate("Outlook.Application")
outlookNameSpace <- OutApp$GetNameSpace("MAPI")
fld <- outlookNameSpace$GetDefaultFolder(6)

# Check that we got the right folder
Cnt <- fld$Items()$Count()
emails <- fld$items
list_Text_Body <- list()

for(i in 1 : Cnt)
{
  print(i)
  list_Text_Body[[i]] <- emails(i)[["Body"]]
}
0
Emmanuel Hamel On

To sort the emails by time, you can use the field ReceivedTime as follows :

library(RDCOMClient)

## create outlook object
OutApp <- COMCreate("Outlook.Application")
outlookNameSpace <- OutApp$GetNameSpace("MAPI")
fld <- outlookNameSpace$GetDefaultFolder(6)

# Check that we got the right folder
Cnt <- fld$Items()$Count()
emails <- fld$items
list_Text_Body <- list()
list_Received_Time <- list()

for(i in 1 : Cnt)
{
  print(i)
  list_Text_Body[[i]] <- emails(i)[["Body"]]
  list_Received_Time[[i]] <- tryCatch(emails(i)[["ReceivedTime"]], error = function(e) NA)
}

vector_Text_Body <- unlist(list_Text_Body)
vector_Received_Time <- unlist(list_Received_Time)
vector_Text_Body_Ordered <- vector_Text_Body[order(vector_Received_Time)]