3

I have an R script that I want to automatically send an email using Microsoft Outlook after it has finished completing. I'm using the "RDCOMClient" package and I want to add multiple attachments to the email.

Here's the code that I'm trying to use:

library(RDCOMClient)

OutApp <- COMCreate("Outlook.Application")

outMail = OutApp$CreateItem(0)

outMail[["To"]] = paste("recipient@account.com","another@gmail.com", sep=";", collapse=NULL)
outMail[["subject"]] = "some subject"
outMail[["body"]] = "some body"
outMail[["attachments"]]$Add("C:/Path/To/The/Attachment/File.ext")

outMail$Send()

I tried using paste for the attachments like the "To" option but I'm 99% sure that is what broke the attachments because it works with just one. It works perfectly for adding multiple recipients. Does anyone know how I can add multiple attachments with this package?

JohnN
  • 968
  • 4
  • 13
  • 35
  • For anyone else struggling with this issue: I noticed that RDComclient needs me to use the FULL file path to attach images - don't rely on using a part of a path if you've set your workspace. – Nova Sep 09 '20 at 13:54

2 Answers2

7

Just add another attachment line:

outMail[["attachments"]]$Add("C:/Path/To/The/Attachment/File.ext")
outMail[["attachments"]]$Add("C:/Path/To/The/Attachment/File2.ext")

Or map(loop) over an attachment object:

attachments <- c("C:/Path/To/The/Attachment/File.ext",
                 "C:/Path/To/The/Attachment/File2.ext")

purrr::map(attachments, ~ outMail[["attachments"]]$Add(.))
Tunn
  • 1,506
  • 16
  • 25
0

I think I know how to solve this problem. I do send multiple attachments at once almost every day using R.

First, before you do the for function, you have to set your work directory to be the one where your files are saved, then you are good to run the code.

setwd("path")
      for(j in 1:length(dir())){
          outMail[["Attachments"]]$Add(paste(path,dir()[j],sep="/"))
      }

Sorry, if I am not being clear enough, it is first answer on StackOverFlow. Hope you get it!

Lucas Bianchi
  • 57
  • 1
  • 7