如何在Windows中发送带有R附件的电子邮件

时间:2010-05-21 21:22:12

标签: r email sendmailr

我有一个从Windows机器运行的预定R脚本。

完成后,我希望此脚本能够自动发送附带一些日志文件的电子邮件。

使用shell()和其他一些脚本是可能的,但我想知道R内是否有更好的解决方案。 感谢。

8 个答案:

答案 0 :(得分:44)

sendmailR适用于Windows 7.我引用了http://cran.es.r-project.org/web/packages/sendmailR/sendmailR.pdf

smtpServer = Outlook 2010的信息位于文件中 - >帐户设置 - >帐户设置 - >双击您的帐户 - > “服务器”框中的文字

library(sendmailR)

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

#####send plain email

from <- "you@account.com"
to <- "recipient@account.com"
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)

此外,可以通过将另一个mime_part添加到msg列表来发送多个文件,如下所示(我也将其压缩):

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)

答案 1 :(得分:15)

使用mailR - 它适用于身份验证,附件,它会自动发送txt消息以及html等。

mailR需要rJava,有时可能会有点痛苦。在Windows上我没有遇到任何问题。在ubuntu上,这解决了我遇到的一个问题:

sudo apt-get install openjdk-jdk 

在R

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

(如果您在使用rJava时遇到问题 - 在终端尝试sudo R CMD javareconf

mailR易于使用,并且在github页面上有详细记录。

来自documentaion的例子

library(mailR)
send.mail(from = "sender@gmail.com",
          to = c("recipient1@gmail.com", "recipient2@gmail.com"),
          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)

注意:您的smtp服务器可能会发现过度使用可疑。例如,情况就是这种情况。 Gmail中。因此,在发送几封邮件后,您可能需要登录gmail account并查看该帐户是否已暂时停用。另请注意,如果您使用具有双因素身份验证的Gmail帐户,则需要使用an application specific password

答案 2 :(得分:10)

你愿意接受推特信息吗?您可以使用Rcurl向Twitter发布更新,然后可以将其作为文本转发到您的手机,或通过通知设置转发到您的电子邮件。

见这里:http://www.sakana.fr/blog/2007/03/18/scripting-twitter-with-curl/

答案 3 :(得分:6)

您是否已查看sendmailR套餐了吗?它允许SMTP提交消息,您可以编辑该功能以允许附件。然后,如果它只有一个日志文件,那么你提到的shell()可能是值得的。

答案 4 :(得分:4)

对于Windows,可以将VB脚本解析(参见例如http://www.paulsadowski.com/wsh/cdo.htm),然后通过shell调用它。

这可能如下所示:

SendMail <- function(from="me@my-server.de",to="me@my-server.de",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")
}

答案 5 :(得分:3)

只想提醒想要通知twilio服务的自我通知功能的人,他们提供免费服务,将短信发送到您自己的手机。使用R的演练https://dreamtolearn.com/ryan/data_analytics_viz/78

附上示例代码,只需将凭据替换为您自己的凭据。

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"))

答案 6 :(得分:0)

后来,但是您可以避免像R-Help中的this example那样,通过正确使用RDCOMClient来炮轰vbscript。

> sendEmail(ema = "r-help at r-project.org", 
        name = "R-help mailing list",
        subject = "How to send Email from R using the RDCOMClient"
        msgBody = "here is the body of the message")

The package RDCOMClient is available at http://www.omegahat.org/RDCOMClient.

"sendEmail" <-
function(ema, name, subject, msgBody, deliverNow = TRUE)
{
   require(RDCOMClient)

   ema <- paste("SMPT:", ema, sep="")   ## prepend protocol to address

   ## create an e-mail session 
   session <- COMCreate("Mapi.Session") 
   session$Logon()

   ## add a message to the outbox collection of messages
   outbox <- session[["Outbox"]]
   msg <- outbox[["Messages"]]$Add(subject, msgBody)

   ## add recipient's name  (TODO: addMultiple() or loop, if many recipients)
   msg[["Recipients"]]$Add(name, ema) 
   msg$Send()
   if(deliverNow)
      msg$DeliverNow()

   session$Logoff()   ## wrap up
}

答案 7 :(得分:0)

这是用于使用“ mailR”包发送电子邮件的简单代码段

List of 2
 $ :List of 2
  ..$ title :'data.frame':  1 obs. of  2 variables:
  .. ..$ id   : Factor w/ 1 level "1a": 1
  .. ..$ title: Factor w/ 1 level "first title": 1
  ..$ author:'data.frame':  2 obs. of  2 variables:
  .. ..$ first_name: Factor w/ 2 levels "Alice","Susan": 2 1
  .. ..$ last_name : Factor w/ 2 levels "Johnson","Smith": 2 1
 $ :List of 2
  ..$ title :'data.frame':  1 obs. of  2 variables:
  .. ..$ id   : Factor w/ 1 level "2b": 1
  .. ..$ title: Factor w/ 1 level "second_title": 1
  ..$ author:'data.frame':  2 obs. of  2 variables:
  .. ..$ first_name: Factor w/ 2 levels "Mary","Sarah": 2 1
  .. ..$ last_name : Factor w/ 2 levels "Davis","Proctor": 1 2