如何使用R发送/接收(SMTP / POP3)电子邮件? [英] How can I send/receive (SMTP/POP3) email using R?

查看:268
本文介绍了如何使用R发送/接收(SMTP / POP3)电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我强烈怀疑最有反应的答案是这是工作的错误工具。我承认R可能不是特别适合发送和接收电子邮件,但它是我最了解的脚本语言。我希望找到发送和接收短信的方法。有没有人知道在Windows平台上这样做的确定方法?我可能可以使用BLAT和GetMail的组合,但是优先选择本机R解决方案。



编辑:可接受的解决方案应该是能够与需要SSL的服务器进行接口。



编辑2:我提供了一个80%的答案。可悲的是,R本土的方式没有被证明。相反,我使用系统调用和命令行程序的不合理组合,这些程序可能在平台之间不兼容。 R本机呼叫将需要挖掘POP3服务器喜欢与连接的客户端进行交流的方式,并了解我目前没有的SSL。仍然鼓励其他答案。

  ##注意:其他程序都包含在R函数和系统调用中。 
#他们每个都有自己的许可证,可能或可能不允许在这里使用建议
#这里使用的程序:
#STunnel:http://www.stunnel.org/;提供SSL隧道,但需要OpenSSL
#OpenSSL:http://www.openssl.org/; OpenSSL实际提供SSL
#请注意,这些.dll应该与stunnel exe一起放置。
#另请注意,libssl32.dll可能需要从ssleay32.dll重命名
#Microsoft Visual C ++ 2008 Redistributable(可能需要SSL .dlls正常工作)
#Blat: http://www.blat.net;一个公共域SMTP发送程序
#Getmail是免费的非商业用途。如果您在商业环境中使用,则需向Tim Charron支付50美元的费用。

#Stunnel是一个TSR,所以如果有问题,它将需要从任务管理器中被杀死。如果您愿意将其安装为服务,您可以调整我的代码来启动和停止服务。
#我当前的代码不会为stunnel创建一个完整版的应用程序的.conf文件。检查http://spampal.sanesecurity.com/manual_eng/servers/stunnel/stunnel.htm#sconfig21以创建相应的配置文件。

#根据需要设置配置值
## 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

#设置邮件功能分配要使用的用户名和密码以及启动stunnel的smtp和pop3服务器(并假定stunnel.conf文件存在,设置正确)。
setMail< - function(user,pw,SSL = FALSE,smtp =127.0.0.1:259,pop3 =127.0.0.1:1109)
{
if(SSL
{
print(启动stunnel;你将需要从任务管理器中删除)
system(stunnel.loc,wait = FALSE)
Sys.sleep(2)#启用它的时间
}
return(list(user = user,pw = pw,smtp = smtp,pop3 = pop3,SSL = SSL))


#函数发送邮件,myMail是来自setMail的结果列表
sendmail< - 函数(myMail,to,subject,msg,VERBOSE = FALSE)
{
writeLines(msg,out.txt,sep =\\\
,useBytes = FALSE)
targ< - paste(getwd(),/ out.txt,sep = )
调用< - 粘贴(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)}
}

#函数来获取邮件,myMail是来自setMail的结果列表;它返回一个列表,其中包含所有未解析的元素的一个元素,另一个列表提供服务器上剩余的消息数。
getmail< - function(myMail,VERBOSE = FALSE)
{
unlink(MSG1.txt)#drop previous get
#download next message
call < - 粘贴(GetMail.loc,-u,myMail $ user,-pw,myMail $ pw,-s,strsplit(myMail $ pop3,:)[[1]] [1] ,
-port,strsplit(myMail $ pop3,:)[[1]] [2],-n 1,sep =)
res < call,intern = TRUE)
if(VERBOSE){print(res)}
nmsgtxt < - res [grep(server on the server,res)]
nstart< - regexpr(有,nmsgtxt)
nend< - regexpr(服务器上的消息,nmsgtxt)
nmess< - as.numeric(substr(nmsgtxt,10,nend- 1)) - 1
x< - readLines(MSG1.txt, - 1)
return(list(message = x,remaining = nmess))
}

用例:简单地说,我需要让R能够发送一个消息,其内容在R脚本中的其他位置确定为SMTP服务器。参与者将收到电子邮件并作出回应。我需要从我的POP3服务器检索他们的响应,并将其存储在一个R数据结构中,以便我可以对它进行后期处理。在实践中,我正在建立一种通过R进行经验抽样的方法。也就是说,R可以通过电子邮件发送参与者今天你好吗(1 = Bad; 7 = Great)?参与者可以回应4,我可以在数据库中匹配问题,答复等等进行统计分析。

解决方案

从Pop服务器拉取邮件



为了实现@JorisMeys利用其他语言的想法,我采取了使用Python和rJython包从Gmail(超过ssl)提取邮件。 Jython是在Java虚拟机上实现的Python,所以使用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(\'yourGmailAddy@gmail.com\'))
rJython $ exec(M.pass_(\'你的GmailPassword\'))
rJython $ exec(numMessages = len(M.list()[1]))
numMessages< - rJython $ get(numMessages)$ getValue )

#抓取消息第一。在这里循环
#需要更多消息
rJython $ exec(msg = M.retr(1)[1])
emailContent< - rJython $ get(msg)

#将消息转换成列表
contentList< - as.list(emailContent)
#所以我们有一个R对象的Java对象
#为了获得更多的本机R列表,我们必须
#yank每个Java项目的字符串

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

messageAsList< - messageToList(contentList)
messageAsList


I strongly suspect the most upvoted answer will be "that is the wrong tool for the job". I acknowledge that R may not be particularly well suited for sending and receiving email but it is the scripting language I know best. I am hoping to find a way to send and receive short emails in R. Does anybody know an established way to do this on a Windows platform? I might be able to use a combination of BLAT and GetMail but a native R solution would be preferred.

Edit: An acceptable solution should be able to interface with servers that require SSL.

Edit 2: I provide my stab at a 80% answer. Sadly an R native way is not demonstrated. Instead I use an unholy combination of system calls and command line programs that is likely to not be compatible across platforms. R native calls will require digging into the way POP3 servers like to talk to connected clients and an understanding of SSL that I don't currently have. Other answers are still encouraged.

##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))
}

Usage case: Simply put, I need to have R be able to send a message whose content is determined elsewhere in the R script to an SMTP server. Participants will receive the email and respond to it. I need to retrieve their response from my POP3 server and store it in an R data structure so that I can perform post processing on it. In practice, I'm establishing a way to do experience sampling via R. That is, R can email a participant "How are you today (1 = Bad; 7 = Great)?" The participant can respond "4", and I can match the question asked, the response, and so on in a database for statistical analysis.

解决方案

Pulling messages from a Pop server

To take a stab at implementing @JorisMeys idea of taking advantage of other languages, I took a stab at pulling mail from Gmail (over ssl) using Python and the rJython package. Jython is Python implemented on the Java virtual machine, so using rJython feels to me a bit like using R to call Java that then pretends to be Python.

I find rJython pretty easy for simple things, but since I'm not well versed in S4 objects and (r)Java I sometimes struggle to properly manipulate the return objects from rJython. But, it works. Here's a basic construct that will pull a single message from a Gmail account:

library(rJython)

rJython <- rJython( modules = "poplib")

rJython$exec("import poplib")
rJython$exec("M = poplib.POP3_SSL('pop.gmail.com', 995)")
rJython$exec("M.user(\'yourGmailAddy@gmail.com\')")
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

这篇关于如何使用R发送/接收(SMTP / POP3)电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆