I found a great article (here) to successfully execute an R program through a combination of a .bat file and Windows (7) Task Scheduler command. Then I used the top rated answer to this question in order to send an email through R.
When I simply execute the R program in R, it emails beautifully. When I run the Windows Task Scheduler to execute the .bat file (which executes the R program), it will create the file that I want but it fails to email. I'm reaching out to this community to see if there are some ideas why the email will not send through the .bat method.
The code below creates a simple .csv file, writes it to my desired path, and then emails it out:
t <- "mission accomplished overnight!"
setwd("C:/Users/bshelto1/Documents/testtoremove1/scheduler_test")
write.csv(t, "mission_accomplished.csv", row.names = FALSE)
library(RDCOMClient)
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] <- "my_email@gmail.com"
outMail[["subject"]] <- "i hope this works"
outMail[["body"]] <- "mission accomplished!"
outMail[["Attachments"]]$Add("C:\\Users\\bshelto1\\Documents\\testtoremove1\\scheduler_test\\mission_accomplished.csv")
outMail$Send()
As I mentioned, when I run the above program in R, it works great (i.e., it creates the file and emails it with attachment).
The next part was creating the .bat file to execute the R program. The .bat code is below:
@echo off
"C:\Users\bshelto1\Documents\R\R-3.2.0\bin\x64\R.exe" CMD BATCH C:\Users\bshelto1\Documents\testtoremove1\scheduler_test\mission_test.R
The final part was creating the Windows Task Scheduler command to completely automate the job. The R code is below:
recurrence <- "once"
task_name <- "Test4"
bat_loc <- "C:\\Users\\bshelto1\\Documents\\testtoremove1\\scheduler_test\\task.bat"
time <- "07:52"
system(sprintf("schtasks /create /sc %s /tn %s /tr \"%s\" /st %s", recurrence, task_name, bat_loc, time))
I've actually narrowed the issue down to the .bat file. If I just run the .bat file, it creates the .csv file by the R program, but won't send the email. Any ideas what would be causing the .bat file to not execute the email portion of the R code?