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

发布于 2024-09-02 16:08:18 字数 151 浏览 6 评论 0原文

我计划了一个从 Windows 计算机运行的 R 脚本。

完成后,我希望这个脚本自动发送一封电子邮件,并附加一些日志文件。

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

I have a scheduled an R script running from a windows machine.

After it finishes, I wish this script to automatically send an email with some log file attached.

Using shell() with some other scripts may be possible, but I was wondering if there is a better solution within R.
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

行至春深 2024-09-09 16:08:19

对于那些建议使用“mailR”的人来说——这是可行的方法,但在 ubuntu 上安装起来很困难。这是在 ubuntu 上安装“javaR”的资源,它允许您安装“mailR”

https://www.r-bloggers.com/2018/02/installing-rjava-on-ubuntu/

For those who suggested using 'mailR' - this is the way to go, but it is difficult to install of ubuntu. Here is a resource to install 'javaR' on ubuntu which will allow you to install 'mailR'

https://www.r-bloggers.com/2018/02/installing-rjava-on-ubuntu/

千仐 2024-09-09 16:08:19

虽然已经晚了,但您可以通过正确使用 RDCOMClient 来避免使用 vbscript,如 此示例来自 R-Help。

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

Late to this, but you can avoid shelling out to vbscript by using RDCOMClient correctly, as in this example from R-Help.

> 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
}
黑寡妇 2024-09-09 16:08:18

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

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

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)

sendmailR works for me on Windows 7. I referenced http://cran.es.r-project.org/web/packages/sendmailR/sendmailR.pdf

smtpServer= info for Outlook 2010 is in File -> Account Settings -> Account Settings -> double click your account -> text in "Server" box

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)

In addition, multiple files can be sent by adding another mime_part to the msg list as follows (I also condensed it):

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)
并安 2024-09-09 16:08:18

使用 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 页面上有详细记录。

文档中的示例

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)

注意:您的 smtp 服务器可能会发现过度使用可疑。例如gmail 就是这种情况。因此,发送几封邮件后,您可能需要登录 gmail 帐户,看看是否帐户已被暂时禁用。另请注意,如果您使用采用双因素身份验证的 Gmail 帐户,则需要使用应用程序专用密码

Use mailR - it works with authentication, attachments, it automatically send txt message along with html and more.

mailR requires rJava which can be a bit of a pain sometimes. On windows I haven't had any problems. On ubuntu this solved the one issue I've had:

sudo apt-get install openjdk-jdk 

in R

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

(if you have trouble with rJava - try sudo R CMD javareconf in terminal)

mailR is easy to work with and well documented on the github page.

Example from the 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)

Note: your smtp server might find excessive use suspicious. This is the case with e.g. gmail. So after sending a few mails you probably have to log in to the gmail account and see if the account has been temporarily disabled. Also note that if you use a gmail account with two-factor authentication you need to use an application specific password.

烟─花易冷 2024-09-09 16:08:18

您愿意接受 Twitter 消息吗?您可以使用 Rcurl 将更新发布到 Twitter,然后可以将其以文本形式转发到您的手机,或者通过通知设置转发到您的电子邮件。

请参阅此处:http://www.sakana.fr /blog/2007/03/18/scripting-twitter-with-curl/

Would you settle for a twitter message? You could use Rcurl to post an update to twitter, which can then be forwarded to your cell phone as a text, or to your email via the notification settings.

See here: http://www.sakana.fr/blog/2007/03/18/scripting-twitter-with-curl/

心清如水 2024-09-09 16:08:18

您研究过 sendmailR 包了吗?它允许 SMTP 提交消息,您可以编辑该功能以允许附件。话又说回来,如果它只有一个日志文件,那么正如您提到的那样,使用 shell() 可能是值得的。

Have you looked into the sendmailR package yet? It allows SMTP to submit a message and you could probably edit the function to allow an attachment. Then again, if its only one log file it might just be worth it to use shell() as you mentioned.

为你拒绝所有暧昧 2024-09-09 16:08:18

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

这可能看起来像这样:

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

For Windows one might parse together a VB-Script (see e.g. http://www.paulsadowski.com/wsh/cdo.htm ) and then call it via shell.

This might look like this:

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")
}
蘑菇王子 2024-09-09 16:08:18

只是想提醒那些想要 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"))

Just want to remind people who wants self-notifying feature of a service called twilio, they provide free service to send sms to your own cellphone. A walk-through using R is available here https://dreamtolearn.com/ryan/data_analytics_viz/78

An example code is attached, just replace the credentials with the ones of your own.

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"))
回忆追雨的时光 2024-09-09 16:08:18

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

library(mailR)

# 1. Sender
sender <- "[email protected]"

# 2. Recipients
recipients <- c("[email protected]", "[email protected]")

# 3. Attached files
list_files_attached_location <- c("mtcars.csv")
list_files_attached_names <- c("mtcars name")
list_files_attached_description <- c("mtcars desc")

# 4. Send email
tryCatch({
  send.mail(from = sender,
            to = recipients,
            subject = "Your subject",
            body = "Your mail body",
            smtp = list(
              host.name = "smtp.gmail.com", 
              port = 465,
              user.name = sender,
              passwd = "psw", 
              ssl = TRUE),
            authenticate = TRUE,
            send = TRUE,
            attach.files = list_files_attached_location,
            file.names = list_files_attached_names,
            file.descriptions = list_files_attached_description,
            debug = TRUE
  )
}, 
error = function(e) {
  print(e)
  stop()
})

Here is a simple code snippet for sending an e-mail by using "mailR" package

library(mailR)

# 1. Sender
sender <- "[email protected]"

# 2. Recipients
recipients <- c("[email protected]", "[email protected]")

# 3. Attached files
list_files_attached_location <- c("mtcars.csv")
list_files_attached_names <- c("mtcars name")
list_files_attached_description <- c("mtcars desc")

# 4. Send email
tryCatch({
  send.mail(from = sender,
            to = recipients,
            subject = "Your subject",
            body = "Your mail body",
            smtp = list(
              host.name = "smtp.gmail.com", 
              port = 465,
              user.name = sender,
              passwd = "psw", 
              ssl = TRUE),
            authenticate = TRUE,
            send = TRUE,
            attach.files = list_files_attached_location,
            file.names = list_files_attached_names,
            file.descriptions = list_files_attached_description,
            debug = TRUE
  )
}, 
error = function(e) {
  print(e)
  stop()
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文