How to retrieve Outlook inbox emails using R RDCOMClient?

早过忘川 提交于 2019-11-27 19:56:01

Here is some sample code I got to work by trial and error:

library(RDCOMClient)

folderName = "AUX"

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

folder <- outlookNameSpace$Folders(1)$Folders(folderName)
# Check that we got the right folder
folder$Name(1)

emails <- folder$Items

# Can't figure out how to get number of items, so just doing first 10
for (i in 1:10)
{
  subject <- emails(i)$Subject(1)
  # Replace "#78" with the text you are looking for in Email Subject line
  if (grepl("#78", subject)[1]){
    print(emails(i)$Body())
    break
  } 
}

Sorry, but I don't know why some of these COM object require parameters (like Subject(1)), but others don't (like Body()). This worked for me on Outlook 2013, but it should also work on all versions of Outlook from 2007 on.

To get more info on the Outlook Object model I would suggest you either get Ken Slovak's Outlook 2007 book (still relevent for later versions of Outlook), or else check out my personal website, http://www.gregthatcher.com (check out the "Scripts" section -- I have been compiling these for many years.)

folderName = "foldername"

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

fld <- outlookNameSpace$GetDefaultFolder(6)

# Check that we got the right folder
fld = fld$folders(folderName)

Cnt = fld$Items()$Count()

emails <- fld$items

df = data.frame(sno = 1:Cnt,Text = "",stringsAsFactors=FALSE)

for(i in seq(Cnt)){
  d = as.data.frame(emails(i)$Body(), stringsAsFactors=FALSE)
  df$Text[i] = d[1]
  df$Sender[i] = emails(i)[['SenderName']]
  df$To[i] = emails(i)[['To']]
  df$sub[i] = emails(i)[['subject']]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!