Parmenides
Parmenides

Reputation: 3

I need to send some emails in a loop changing receiver names in each iteration

I have a text file in one column are the receiver surnames, and on the other their email addresses. I am using the package mailR in R to send them a personalised text.

I have tried putting it in a for loop but it is not working.

install.packages("mailR", dep = T)
library(mailR)

email.addresses <- c("[email protected]","[email protected]","[email protected]")
names.addresses <- c("name1","name2","name3")

for (i in length(email.addresses)) {


dear <- "Dear "
comma <- ","
dr <- "Mr. "
name <- names.addresses[i]
subject <- paste(dear, dr, name, comma, sep = "")

email <- send.mail(from = "sender <[email protected]>",
             to = email.addresses[i],
             subject = "subject header",
             body = paste(subject, "some text", sep = "\n\n"),
             encoding = "utf-8",
             smtp = list(host.name = "smtp.gmail.com", port = 465,
             user.name = "username", passwd = "password", ssl = T),
             authenticate = TRUE,
             send = TRUE)
}

What gets actually sent is only to the last email address of the list email.addresses - "[email protected]".

Any ideas?

Upvotes: 0

Views: 460

Answers (1)

Arkning
Arkning

Reputation: 181

I just run your code and you should just change your for loop by :

for (i in 1:length(email.addresses))

Next time try to print your data (I mean by that to print the variable i) and you would have seen that your loop only does one loop, because length(email.addresses) = 3 but when using for loop you need to give 2 values, the begin and the end. 1:length(email.addresses) is the same as c(1:length(email.addresses)) and it means that it will take all the values between 1 and length(email.addresses).

Upvotes: 2

Related Questions