0

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 Answers2

1

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"]]
}
Emmanuel Hamel
  • 1,769
  • 7
  • 19
  • When i run it all, the for loop doesnt out put anything – Jacob Nordstrom Sep 28 '22 at 23:25
  • Do you have emails in your outlook? On my end, the code works very well. You can print the content of list_Text_Body with print(list_Text_Body) – Emmanuel Hamel Sep 29 '22 at 03:16
  • I think i understand how this works now. Yes i do have emails in my inbox, if i were to want to pull the most recent email, how would i call that? print(list_Text_Body[[??]]) Secondary question, is it possible to grab emails from a secondary inbox – Jacob Nordstrom Sep 30 '22 at 15:50
  • I am not sure of what you mean by a secondary inbox. Can you give more details? – Emmanuel Hamel Sep 30 '22 at 16:44
0

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)]
Emmanuel Hamel
  • 1,769
  • 7
  • 19