Я сильно подозреваю, что самый верный ответ будет «это неправильный инструмент для работы». Я признаю, что R не может быть особенно хорошо подходит для отправки и получения электронной почты, но это язык сценариев, который я знаю лучше всего. Я надеюсь найти способ отправки и получения коротких писем в R. Кто-нибудь знает, как это сделать на платформе Windows? Я мог бы использовать комбинацию BLAT и GetMail, но предпочтительным было бы решение на основе R.Как отправить/получить (SMTP/POP3) адрес электронной почты, используя 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 сценария на сервер SMTP. Участники получат электронное письмо и ответят на него. Мне нужно получить ответ с моего сервера POP3 и сохранить его в структуре данных R, чтобы я мог выполнять пост-обработку на нем. На практике я устанавливаю способ проведения выборки через R. То есть R может отправить по электронной почте участника «Как вы сегодня (1 = Плохо, 7 = Отлично)?» Участник может ответить «4», и я могу ответить на вопрос, ответ и т. Д. В базе данных для статистического анализа.
Похожей (но не дублировать причину SSL) http://stackoverflow.com/questions/2885660/how-to-send-email-with-attachment-from-r-in-windows и http://stackoverflow.com/questions/3572607/sendmailr-part2 -sending-files-as-mail-attachments – Marek
Что происходит с тоном Edit2 и Edit3? Это действительно нужно? –
На стороне sidenote Perl (и по расширению Python) по-прежнему является основным языком сценариев, используемым в качестве бэкэнда для многих веб-сайтов. Он содержит множество функций для (автоматической) отправки и получения электронной почты (многие списки рассылки используют эти функции в Perl). Я тоже программист по необходимости, но я рад, что научился работать с более чем одним «инструментом» (т. Е. Языком). В конечном счете, это лучший способ пойти. Кроме того, Perl и R могут быть связаны. Или Python с курса, он тоже может это сделать. –