Vaibhav Chawla
Vaibhav Chawla

Reputation: 9

How to attach a file of multiple extension in mailR (Rstudio)

I want to attach files of different extension to a mail. My some id has pdf file and some has excel file. So i generated the path for both type of files. But when i attach the files its give me a error attach.files must link to a valid file. which is right that file not exists. Can anyone please help me in the same.

enter code here

data_send<-read.csv('/Users/vaibhav.chawla/Downloads/manual.csv')


smtp<-list(host.name="smtp.gmail.com",smtpPortSMTP=465,user.name="[email protected]",passwd='xxxx',ssl=T)
i=1

for (i in i:nrow(data_send)) {



  from <- "xxxxx"
  to<-c(paste0(data_send$mail[i]))
  cc<-c(paste0(data_send$amail[i]))
  subject <-paste0("Summary May 01, 2020 to May 27, 2020")
  body <-paste0("Hello")
  filtetype <- c(".xlsx",".pdf")
  path<-c(paste("/Users/vaibhav.chawla/Downloads/Excel/",data_send$id[i],filetype,sep=""))
  mailSend<-send.mail(from=from,to=to,cc=cc,subject=subject,body = body,smtp=smtp,authenticate = T,send = T,html=T,inline = T,attach.files = c(path))
  print(paste0(i,". Mail sent to ",data_send$id[i]))

}

Upvotes: 0

Views: 548

Answers (1)

dario
dario

Reputation: 6485

Using the base funciton file.exists to get a boolean vector specifying for each file in path if it was found. If any files are found use the attach.file argument in the call to send.mail, again using the valid_paths vector to select only the found paths. If no files were found omit the attach.file argument.

valid_paths <- file.exists(path)
if (any(valid_paths))) {
    mailSend<-send.mail(from=from,to=to,cc=cc,subject=subject,body = body,smtp=smtp,authenticate = T,send = T,html=T,inline = T,attach.files =path[valid_path])
} else {
    mailSend<-send.mail(from=from,to=to,cc=cc,subject=subject,body = body,smtp=smtp,authenticate = T,send = T,html=T,inline = T)
}

Upvotes: 0

Related Questions