0

I have a data frame with two variables: classification and email id. The reproducible example of the data frame is as follows:

structure(list(Classification = structure(c(1L, 1L, 1L), .Label = "bills", class = "factor"), 
    FromMailId = structure(c(1L, 1L, 1L), .Label = "bimbilikkibimbi@yahoo.com", class = "factor")), .Names = c("Classification", 
"FromMailId"), row.names = c(NA, 3L), class = "data.frame")

I am using library(mailR) to send mails. I have to customise the mail delivery basis the value in Classification variable. I was trying to loop through the data frame to pick up the email id depending on the value of the Classification. The following is the code I am using:

for(i in df1$Classification){
        if(i == "bills"){
                library(mailR)
                send.mail(from = "UserName@gmail.com",
                          to = df1$FromMailId[i],
                          subject = paste("Subject: ", "This is a test message"),
                          body = "You have got bills",
                          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "UserName", passwd = "PassWord", ssl = TRUE),
                          authenticate = TRUE,
                          send = TRUE)
        }
}

The above code works perfectly if I change the 'to' email id to an actual email id. But when I reference the same field to a column in the data frame(FromMailId here), I get the following error:

Error in ls(envir = envir, all.names = private) : 
  invalid 'envir' argument

I gathered that I am referencing a specific column in the loop and referring to another column inside send.mail...but not sure how to resolve this.

Apricot
  • 2,925
  • 5
  • 42
  • 88

2 Answers2

0

You're looping over the elements of Classification and trying to use that as a subset index, which won't work. Try this instead:

library(mailR) #No need to have that in the loop
for(i in 1:nrow(df1)){
        if(df1$Classification[i] == "bills"){                    
                send.mail(from = "UserName@gmail.com",
                          to = df1$FromMailId[i],
                          subject = paste("Subject: ", "This is a test message"),
                          body = "You have got bills",
                          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "UserName", passwd = "PassWord", ssl = TRUE),
                          authenticate = TRUE,
                          send = TRUE)
        }
}
Molx
  • 6,816
  • 2
  • 31
  • 47
-1

I believe the df1$FromMailId is a factor. So try converting it in to character.

Either convert the column using df1$FromMailId <- as.character(df1$FromMailId, stringAsFactors = F) or just edit the sendmail code by to = as.character(df1$FromMailId[i]).

Shiva Prakash
  • 1,849
  • 4
  • 21
  • 25
  • Thank you @Shiva Prakash. It was a factor indeed. After converting it to character, it worked. Thank you again. – Apricot Nov 09 '15 at 11:45