如何使用循环从R内发送电子邮件

时间:2015-02-11 08:04:35

标签: r email loops

下面的R代码会向收件人发送电子邮件,这些收件人的电子邮件地址是从名为email的文本文件中读取的。由于Gmail不允许一次发送超过100个,我想使用一个循环,它将发送电子邮件到前100个,然后是101-200,然后是201-300,依此类推。有什么可以帮助我吗?

library(mailR)
sender <- "xyz@gmail.com"
recipients <- scan("email.txt", encoding="UTF-8",character(0))
send.mail(from = sender,
to = recipients,
subject="Subject of the Mail",
body = "Body of the Mail",
smtp = list(host.name = "smtp.gmail.com", port = 465, 
    user.name="convert2latex@gmail.com", passwd="Mypassword", ssl=TRUE),
    authenticate = TRUE, send = TRUE)

2 个答案:

答案 0 :(得分:4)

根据Gmail Sending Limits,您可以通过一封电子邮件发送最多99个地址。也许你想把它们放到BCC领域?以下是Gmail的测试示例(请记住allow unsecure apps first并指定senderuser.namepasswd):

library(mailR)
sender <- "...@gmail.com" # gmail user
# create 5 test addresses from `sender`
testEmails <- paste(sapply(1:5, function(x) sub("(.*)(@.*)", paste0("\\1+test", x, "\\2"), sender)), collapse = "\n") 
cat(testEmails) # print the addresses 
recipients <- scan(file = textConnection(testEmails), encoding="UTF-8",character(0))

## Create a list of vectors of emails with the max size adrPerBatch each
getRecipientBatches <- function(emails, adrPerBatch = 98) {
  cuts <- seq(from = 1, to = length(emails), by = adrPerBatch)
  recipientBatches <- lapply(cuts, function(x) c(na.omit(emails[x:(x+adrPerBatch-1)])))
  return(recipientBatches)
}

## send the 3 test batches à 2/1 address(es)
res <- lapply(getRecipientBatches(recipients, adrPerBatch = 2), function(recipients) {
  send.mail(from =  sender,
            to = sender,
            bcc = recipients,
            subject="Subject of the Mail",
            body = "Body of the Mail",
            smtp = list(host.name = "smtp.gmail.com", 
                        port = 465, 
                        user.name = "...", 
                        passwd = "...", 
                        ssl = TRUE),
            authenticate = TRUE, 
            send = TRUE)
})

答案 1 :(得分:1)

未经测试,但应该为您自己的探索提供跳板。从概念上讲,这类似于for循环,但FUN适用于recipients中每个因素的INDEX。我使用tapply,根据recipients裁减INDEX(随意自行计算)。您可以插入Sys.sleep以阻止&#34;循环&#34;发送太快。 如果您插入browser()作为函数的第一行(并运行它),您将被放置在函数内部,您可以进一步探索它正在做什么。

tapply(X = recipients, INDEX = as.integer(cumsum(rep(1, 252))/100), FUN = function(x, recipients, sender) {
  send.mail(from = sender,
            to = recipients,
            subject="Subject of the Mail",
            body = "Body of the Mail",
            smtp = list(host.name = "smtp.gmail.com", port = 465, 
                        user.name="convert2latex@gmail.com", passwd="Mypassword", ssl=TRUE),
            authenticate = TRUE, send = TRUE)
}, recipients = recipients, sender = sender)