如何使用mailR将不同的内容发送给不同的收件人

时间:2015-09-07 13:37:06

标签: r

我正在尝试向不同的收件人发送不同的内容,但所有收件人都会获得所有内容。有什么帮助吗?

library(mailR)
msg<- data.frame(recipients=c("first@mail.com","second@mail.com","third@mail.com"),
                 messages=c("firstmsg","secondmsg","thirdmsg"))

for ( i in msg$recipients)  
{  
  for (j in msg$messages)  {
    send.mail(from="myemail@mail.com",
              to= i,  
              body =  j,
              subject = "subject",
              encoding = "utf-8",  
              smtp= list(host.name = "smtp.gmail.com", port = 465, 
                         user.name = "myemail@mail.com", passwd = "mypassword", ssl = TRUE),
              authenticate = TRUE,  send = TRUE,  attach.files=NULL,  debug = FALSE)
  }
}

1 个答案:

答案 0 :(得分:1)

您使用的是一个双循环,它会遍历循环中j的每个值的i的每个值。一种方法是使用列表索引:

msg<-data.frame(recipients=c("first@mail.com","second@mail.com",
"third@mail.com"),messages=c("firstmsg","secondmsg","thirdmsg"))

for i in 1:nrow(msg)  
{  
send.mail(from="myemail@mail.com",
to= msg$recipients[i],  
body =  msg$message[i],
subject = "subject",
encoding = "utf-8",  
smtp= list(host.name = "smtp.gmail.com", port = 465, 
user.name = "myemail@mail.com", passwd = "mypassword", ssl = TRUE),
authenticate = TRUE,  send = TRUE,  attach.files=NULL,  debug = FALSE)
}