2015-02-11 85 views
0

下面的R代码将电子邮件发送到其电子邮件地址从名为email的文本文件中读取的收件人。由于Gmail不允许一次发送超过100个邮件,因此我想要使用一个循环发送电子邮件到前100个,然后101-200,然后201-300等。任何人都可以帮助我吗?如何使用循环从R内发送电子邮件

library(mailR) 
sender <- "[email protected]" 
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="[email protected]", passwd="Mypassword", ssl=TRUE), 
    authenticate = TRUE, send = TRUE) 
+0

您是否尝试过一个简单的'for'环(看' “为”'?)?我们很难理解你到底不清楚什么。此外,Gmail可能会监控您的访问,如果您开始垃圾邮件轰炸它们,它们可能会将您锁定,因此您可能需要等待迭代之间的几秒钟。 – 2015-02-11 08:20:15

+0

我并不清楚任何事情。我知道我想做什么,但不知道如何。我不太擅长循环。我试图使用和重复循环,但可以得到任何有价值的东西 – 2015-02-11 09:25:32

回答

4

根据Gmail Sending Limits,您可以使用一封电子邮件发送至多达99个地址。也许你想把这些放到BCC领域?下面是Gmail的一个试验例子(记得allow unsecure apps first并指定senderuser.namepasswd):

library(mailR) 
sender <- "[email protected]" # 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) 
}) 
+0

伟大的工作@lukeA。非常感激 – 2015-02-11 11:09:35

1

这是未经测试,但应该给你一个跳板为自己的探索。从概念上讲,这就像是一个for循环,但是适用于INDEX中的每个因子的recipients。我使用tapply,根据INDEX削减recipients(随时计算您自己的)。您可以插入Sys.sleep以防止“循环”发送太快。 如果您插入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="[email protected]", passwd="Mypassword", ssl=TRUE), 
      authenticate = TRUE, send = TRUE) 
}, recipients = recipients, sender = sender) 
相关问题