Подтвердить что ты не робот

Как я могу отправить/получить (SMTP/POP3) электронную почту с помощью R?

Я сильно подозреваю, что самый верный ответ будет "это неправильный инструмент для работы". Я признаю, что R не может быть особенно хорошо подходит для отправки и получения электронной почты, но это язык сценариев, который я знаю лучше всего. Я надеюсь найти способ отправки и получения коротких писем в R. Кто-нибудь знает, как это сделать на платформе Windows? Я мог бы использовать комбинацию BLAT и GetMail, но предпочтительным было бы решение на основе R.

Изменить: Допустимое решение должно иметь возможность взаимодействовать с серверами, которым требуется SSL.

Изменить 2: Я предоставляю свой удар в 80% ответе. К сожалению, родной путь R не продемонстрирован. Вместо этого я использую нечестивую комбинацию системных вызовов и программ командной строки, которые, вероятно, не будут совместимы на разных платформах. R, потребует копания в том, как серверы POP3 любят разговаривать с подключенными клиентами и понимать SSL, которых у меня сейчас нет. Другие ответы по-прежнему приветствуются.

##Note: Other programs are wrapped in R functions and system calls.
#They each have their own licenses which may or may not allow the use suggested here
#Programs used here:
#STunnel: http://www.stunnel.org/; Provides an SSL tunnel but requires OpenSSL 
#OpenSSL: http://www.openssl.org/; OpenSSL to actually provide SSL
#   Note that these .dlls should be placed with the stunnel exe.
#   Also note that libssl32.dll may need to be renamed from ssleay32.dll
#Microsoft Visual C++ 2008 Redistributable (may be required for the SSL .dlls to work correctly)
#Blat: http://www.blat.net; a public domain SMTP sending program
#Getmail is free for non-commercial use. If you use it in a business environment, then a fee of $50 USD is payable to Tim Charron. 

#Stunnel is a TSR, so it will need to be killed from the task manager if there is an issue.  If you are willing to install it as a service you may be able to tweak my code to start and stop the service.  
#My current code does not create .conf file for stunnel the way a full version ought.  Check http://spampal.sanesecurity.com/manual_eng/servers/stunnel/stunnel.htm#sconfig21 to create the appropriate configuration file.

#Set the config values as appropriate
##Config##
BLAT.loc <- "c:/Programming/R/Rmail/blat262/full/blat.exe"
GetMail.loc <- "C:/Programming/R/RMail/getmail133/getmail.exe"
stunnel.loc <- "C:/Programming/R/RMail/stunnel/stunnel-4.11.exe"

#The set mail function assigns the username and password to be used as well as the smtp and pop3 servers it starts stunnel (and assumes that the stunnel.conf file is present and set correctly).
setMail <- function(user,pw,SSL=FALSE,smtp="127.0.0.1:259",pop3="127.0.0.1:1109")
{
    if (SSL==TRUE)
    {
        print("Starting stunnel; you will need to kill this from the task-manager")
        system(stunnel.loc,wait=FALSE)
        Sys.sleep(2) #Give it time to start 
    }
    return(list(user=user,pw=pw,smtp=smtp,pop3=pop3,SSL=SSL))
}

#function to send mail, myMail is the resulting list from setMail
sendmail <- function(myMail, to, subject, msg,VERBOSE=FALSE)
{
    writeLines(msg, "out.txt", sep = "\n", useBytes = FALSE)
      targ <- paste(getwd(),"/out.txt",sep="")
    call <- paste(BLAT.loc, ' "',targ,'" -subject "',subject,'" -to ',to," -u ",myMail$user," -pw ",myMail$pw, " -f ",myMail$user, " -debug -server ",myMail$smtp,sep="")
    res <- system(call,intern=TRUE)
    if (VERBOSE) {return(res)}
}

#function to get mail, myMail is the resulting list from setMail; it returns a list with one element that contains everything unparsed, another list provides the number of messages remaining on the server.
getmail <- function(myMail,VERBOSE=FALSE)
{      
    unlink("MSG1.txt") #drop previous get
    #download next message
    call <- paste(GetMail.loc," -u ",myMail$user," -pw ",myMail$pw," -s ",strsplit(myMail$pop3,":")[[1]][1],
        " -port ",strsplit(myMail$pop3,":")[[1]][2]," -n 1",sep="")
    res <- system(call,intern=TRUE)
    if (VERBOSE) {print(res)}
    nmsgtxt <- res[grep("messages on the server.",res)]
    nstart <- regexpr("There are",nmsgtxt)
    nend <- regexpr("messages on the server.",nmsgtxt)
    nmess <- as.numeric(substr(nmsgtxt,10,nend-1))-1
      x <- readLines("MSG1.txt",-1)
    return(list(message=x,remaining=nmess))
}

Пример использования. Проще говоря, мне нужно, чтобы R мог отправлять сообщение, содержимое которого определено в другом месте R script на SMTP-сервер. Участники получат электронное письмо и ответят на него. Мне нужно получить ответ с моего сервера POP3 и сохранить его в структуре данных R, чтобы я мог выполнять пост-обработку на нем. На практике я устанавливаю способ проведения выборки через R. То есть R может отправить по электронной почте участника "Как вы сегодня (1 = Плохо, 7 = Отлично)?" Участник может ответить "4", и я могу ответить на вопрос, ответ и т.д. В базе данных для статистического анализа.

4b9b3361

Ответ 1

Вытягивание сообщений с сервера Pop

Чтобы принять удар по внедрению идеи @JorisMeys о пользовании другими языками, я взял удар по вытаскиванию почты из Gmail (поверх ssl) с помощью Python и пакета rJython. Jython - это Python, реализованный на виртуальной машине Java, поэтому использование rJython для меня немного напоминает использование R для вызова Java, которое затем претендует на роль Python.

Я считаю rJython довольно простым для простых вещей, но так как я не хорошо разбираюсь в объектах S4 и (r) Java, я иногда пытаюсь правильно манипулировать возвращаемыми объектами из rJython. Но это работает. Вот базовая конструкция, которая вытащит одно сообщение из учетной записи Gmail:

library(rJython)

rJython <- rJython( modules = "poplib")

rJython$exec("import poplib")
rJython$exec("M = poplib.POP3_SSL('pop.gmail.com', 995)")
rJython$exec("M.user(\'[email protected]\')")
rJython$exec("M.pass_(\'yourGmailPassword\')")
rJython$exec("numMessages = len(M.list()[1])")
numMessages <- rJython$get("numMessages")$getValue()

# grab message number one. Loop here if you
# want more messages
rJython$exec("msg = M.retr(1)[1]")
emailContent <- rJython$get("msg")

# turn the message into a list
contentList <- as.list(emailContent)
# so we have an R list... of Java objects
# To get a more native R list we have to
# yank the string from each Java item

messageToList <- function(contentList){
  outList <- list()
  for (i in 1:length(contentList)){
    outList[i] <- contentList[[i]]$toString()
  }
  outList
}

messageAsList <- messageToList(contentList)
messageAsList

Ответ 2

Посмотрите на sendmailR пакет на CRAN.

Ответ 3

С пакетом mailR (http://rpremraj.github.io/mailR/) вы можете отправлять электронные письма с помощью SSL:

send.mail(from = "[email protected]",
          to = c("[email protected]", "[email protected]"),
          subject = "Subject of the email",
          body = "<html>The apache logo - <img src=\"http://www.apache.org/images/asf_logo_wide.gif\"></html>",
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
          attach.files = c("./download.log", "upload.log"),
          authenticate = TRUE,
          send = TRUE)