web-dev-qa-db-fra.com

Comment envoyer un e-mail avec pièce jointe de R dans Windows

J'ai planifié un script R exécuté sur une machine Windows.

Une fois terminé, je souhaite que ce script envoie automatiquement un e-mail avec un fichier journal joint.

L'utilisation de Shell() avec d'autres scripts peut être possible, mais je me demandais s'il y avait une meilleure solution dans R. Merci.

52
ahala

sendmailR fonctionne pour moi sur Windows 7. J'ai référencé http://cran.es.r-project.org/web/packages/sendmailR/sendmailR.pdf

smtpServer = les informations pour Outlook 2010 se trouvent dans Fichier -> Paramètres du compte -> Paramètres du compte -> double-cliquez sur votre compte -> texte dans la zone "Serveur"

library(sendmailR)

#set working directory
setwd("C:/workingdirectorypath")

#####send plain email

from <- "[email protected]"
to <- "[email protected]"
subject <- "Email Subject"
body <- "Email body."                     
mailControl=list(smtpServer="serverinfo")

sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)

#####send same email with attachment

#needs full path if not in working directory
attachmentPath <- "subfolder/log.txt"

#same as attachmentPath if using working directory
attachmentName <- "log.txt"

#key part for attachments, put the body and the mime_part in a list for msg
attachmentObject <- mime_part(x=attachmentPath,name=attachmentName)
bodyWithAttachment <- list(body,attachmentObject)

sendmail(from=from,to=to,subject=subject,msg=bodyWithAttachment,control=mailControl)

De plus, plusieurs fichiers peuvent être envoyés en ajoutant un autre mime_part à la liste des messages comme suit (je l'ai également condensé):

attachmentObject <- mime_part(x="subfolder/log.txt",name="log.txt")
attachmentObject2 <- mime_part(x="subfolder/log2.txt",name="log2.txt")
bodyWithAttachment <- list(body,attachmentObject,attachmentObject2)
45
ARobertson

Utilisez mailR - cela fonctionne avec l'authentification, les pièces jointes, il envoie automatiquement un message txt avec html et plus encore.

mailR nécessite rJava qui peut parfois être un peu pénible. Sur les fenêtres, je n'ai eu aucun problème. Sur Ubuntu, cela a résolu le seul problème que j'ai eu:

Sudo apt-get install openjdk-jdk 

dans R

install.packages("devtools", dep = T)
library(devtools)
install_github("rpremraj/mailR")

(si vous rencontrez des problèmes avec rJava - essayez Sudo R CMD javareconf dans le terminal)

mailR est facile à utiliser et bien documenté sur la page github.

Exemple de la documentaion

library(mailR)
send.mail(from = "[email protected]",
          to = c("[email protected]", "[email protected]"),
          subject = "Subject of the email",
          body = "Body of the email",
          smtp = list(Host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
          authenticate = TRUE,
          send = TRUE,
          attach.files = c("./download.log", "upload.log", "https://dl.dropboxusercontent.com/u/5031586/How%20to%20use%20the%20Public%20folder.rtf"),
          file.names = c("Download log.log", "Upload log.log", "DropBox File.rtf"), # optional parameter
          file.descriptions = c("Description for download log", "Description for upload log", "DropBox File"), # optional parameter
          debug = TRUE)

Remarque: votre serveur smtp peut trouver suspect une utilisation excessive. C'est le cas par ex. Gmail. Donc, après avoir envoyé quelques e-mails, vous devez probablement vous connecter au compte gmail et voir si le compte a été temporairement désactivé. Notez également que si vous utilisez un compte gmail avec une authentification à deux facteurs, vous devez utiliser n mot de passe spécifique à l'application .

15
Andreas

Accepteriez-vous un message Twitter? Vous pouvez utiliser Rcurl pour publier une mise à jour sur Twitter, qui peut ensuite être transmise à votre téléphone portable sous forme de texte ou à votre e-mail via les paramètres de notification.

Voir ici: http://www.sakana.fr/blog/2007/03/18/scripting-Twitter-with-curl/

10
chrisamiller

Avez-vous déjà examiné le package sendmailR? Il permet à SMTP de soumettre un message et vous pourriez probablement modifier la fonction pour autoriser une pièce jointe. Là encore, s'il s'agit d'un seul fichier journal, cela peut valoir la peine d'utiliser Shell() comme vous l'avez mentionné.

6
Stedy

Pour Windows, on peut analyser un VB-Script (voir par exemple http://www.paulsadowski.com/wsh/cdo.htm ) puis l'appeler via Shell.

Cela pourrait ressembler à ceci:

SendMail <- function(from="[email protected]",to="[email protected]",text="Hallo",subject="Sag Hallo",smtp="smtp.my.server.de",user="me.myself.and.i",pw="123"){
require(stringr)
part1 <- "Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory. 
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network). 
Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication 
Const cdoNTLM = 2 'NTLM "

part2 <- paste(paste("Set objMessage = CreateObject(",'"',"CDO.Message",'"',")" ,sep=""),
paste("objMessage.Subject = ",'"',subject,'"',sep=""),
paste("objMessage.From = ",'"',from,'"',sep=""),
paste("objMessage.To = ",'"',to,'"',sep=""),
paste("objMessage.TextBody = ",'"',text,'"',sep=""),
sep="\n")

part3 <- paste(
"'==This section provides the configuration information for the remote SMTP server. 

objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/sendusing\") = 2

'Name or IP of Remote SMTP Server 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/smtpserver\") = ",'"',smtp,'"'," 

'Type of authentication, NONE, Basic (Base64 encoded), NTLM 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/smtpauthenticate\") = cdoBasic 

'Your UserID on the SMTP server 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/sendusername\") = ",'"',user,'"'," 

'Your password on the SMTP server 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/sendpassword\") = ",'"',pw,'"', "

'Server port (typically 25) 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/smtpserverport\") = 25 

'Use SSL for the connection (False or True) 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/smtpusessl\") = False 

'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server) 
objMessage.Configuration.Fields.Item _ 
(\"http://schemas.Microsoft.com/cdo/configuration/smtpconnectiontimeout\") = 60 
objMessage.Configuration.Fields.Update

'==End remote SMTP server configuration section== 

objMessage.Send 
",sep="")

vbsscript <- paste(part1,part2,part3,sep="\n\n\n")
str_split(vbsscript,"\n")
writeLines(vbsscript, "sendmail.vbs")
Shell("sendmail.vbs")
unlink("sendmail.vbs")
}
4
petermeissner

Je veux juste rappeler aux gens qui veulent une fonction d'auto-notification d'un service appelé twilio, qu'ils fournissent un service gratuit pour envoyer des sms à votre propre téléphone portable. Une visite guidée à l'aide de R est disponible ici https://dreamtolearn.com/ryan/data_analytics_viz/78

Un exemple de code est joint, remplacez simplement les informations d'identification par les vôtres.

library(jsonlite)
library(XML)
library(httr)
library(rjson)
library(RCurl)
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))

authenticate_twilio <- "https://[ACCOUNT SID]:[AUTH TOKEN]@api.twilio.com/2010-04-01/Accounts"
authenticate_response <- getURL(authenticate_twilio)
print(authenticate_response)

postForm("https://[ACCOUNT SID]:[AUTH TOKEN]@api.twilio.com/2010-04-01/Accounts/[ACCOUNT SID]/Messages.XML",.params = c(From = "+1[twilio phone#]", To = "+1[self phone#]",Body = "Hello from twilio"))
3
Chen