0

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="vaibhav@xxxx.com",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]))

}
Phil
  • 7,287
  • 3
  • 36
  • 66
  • you should check if a .pfd or a .xlsx files exists in `path`, and only attach the one that does. – Wimpel Jun 05 '20 at 05:24

1 Answers1

0

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)
}
dario
  • 6,415
  • 2
  • 12
  • 26
  • One more help.. If list of to and cc is not in right format my code stops. For eg if id contains some special character [, & /]. So how to ignore this error? – Vaibhav Chawla Jun 05 '20 at 07:33