sendmailR(第 2 部分):将文件作为邮件附件发送

发布于 2024-09-16 16:12:58 字数 1379 浏览 4 评论 0原文

按照 this 相关问题中提供的说明,我能够发送 html 格式的邮件消息。现在的问题是:我应该如何修改以下代码,以便将一个或多个文件(任何类型)附加到此消息?

library(sendmailR)

from <- "<[email protected]>"
to <- c("<[email protected]>","<[email protected]>")
subject <- iconv("Message Title", to = "utf8")

msg <- "<hr size='2' width='33%' style='text-align: left;'><font size='2'>
  <i>This email was sent automatically using <a href='http://finzi.psych.upenn.edu/R/library/sendmailR/html/00Index.html' rel='nofollow' target='_blank'>sendmailR</a>.<br>
  Please do not reply directly to this e-mail.</i></font>"

msg <- iconv(msg, to = "utf8")

sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))

Following the directions provided in this related question, I was able to send html formated mail messages. Now the question is this: How should I modify the following code, in order to attach one or more files (of any type) to this message?

library(sendmailR)

from <- "<[email protected]>"
to <- c("<[email protected]>","<[email protected]>")
subject <- iconv("Message Title", to = "utf8")

msg <- "<hr size='2' width='33%' style='text-align: left;'><font size='2'>
  <i>This email was sent automatically using <a href='http://finzi.psych.upenn.edu/R/library/sendmailR/html/00Index.html' rel='nofollow' target='_blank'>sendmailR</a>.<br>
  Please do not reply directly to this e-mail.</i></font>"

msg <- iconv(msg, to = "utf8")

sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))

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

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

发布评论

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

评论(5

心清如水 2024-09-23 16:12:58

使用 mailR 包(https://github.com/rpremraj/mailR),您可以发送 HTML 电子邮件并另外附加文件如下所示:

send.mail(from = "[email protected]",
          to = c("[email protected]", "[email protected]"),
          subject = "Subject of the email",
          body = "<html>The apache logo - <img src=\"http://www.apache.org/images/asf_logo_wide.gif\"></html>",
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
          attach.files = c("./download.log", "upload.log"),
          authenticate = TRUE,
          send = TRUE)

编辑(2014-05-13):

mailR 已更新为允许不同的字符编码。下面是以 UTF-8 格式发送消息的示例。

send.mail(from = "Sender Name <[email protected]>",
          to = "[email protected]",
          subject = "A quote from Gandhi",
          body = "In Hindi :  थोडा सा अभ्यास बहुत सारे उपदेशों से बेहतर है।
                  English translation: An ounce of practice is worth more than tons of preaching.",
          encoding = "utf-8",
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = T),
          authenticate = TRUE,
          send = TRUE)

With the mailR package (https://github.com/rpremraj/mailR), you could send HTML emails and additionally attach files with ease as below:

send.mail(from = "[email protected]",
          to = c("[email protected]", "[email protected]"),
          subject = "Subject of the email",
          body = "<html>The apache logo - <img src=\"http://www.apache.org/images/asf_logo_wide.gif\"></html>",
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
          attach.files = c("./download.log", "upload.log"),
          authenticate = TRUE,
          send = TRUE)

Edit (2014-05-13):

mailR has been updated to allow different character encodings. Below is an example to send the message as UTF-8.

send.mail(from = "Sender Name <[email protected]>",
          to = "[email protected]",
          subject = "A quote from Gandhi",
          body = "In Hindi :  थोडा सा अभ्यास बहुत सारे उपदेशों से बेहतर है।
                  English translation: An ounce of practice is worth more than tons of preaching.",
          encoding = "utf-8",
          smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = T),
          authenticate = TRUE,
          send = TRUE)
瀞厅☆埖开 2024-09-23 16:12:58

一个有效的(至少对我来说)功能:

sendMessage<-function(contents,subject,from,to,attMIME,attachment,control){    
   msg<-list(contents,sendmailR:::.file_attachment(attachment,attachment,attMIME));
   sendmail(from=from,to=to,subject=subject,msg=msg,control=control);
}

可以像这样使用:

png('a.png');hist(rnorm(700));dev.off()
sendMessage('Here you have a nice histogram:',
'Nice picture',
'[email protected]',
'[email protected]',
'image/png',
'a.png',list(smtpServer="..."))

请注意,此示例发送的消息可能会被标记为垃圾邮件,因为它是一个短文本和一个大图片 - 尽管如此,对于较大的消息,让我们比如说,它应该经过pdf附件。如果没有,您可以考虑添加该消息的文本版本。

编辑(现在不太相关):关于如何制作 MIME 消息的最深入的见解可以找到

A working (for me at least) function:

sendMessage<-function(contents,subject,from,to,attMIME,attachment,control){    
   msg<-list(contents,sendmailR:::.file_attachment(attachment,attachment,attMIME));
   sendmail(from=from,to=to,subject=subject,msg=msg,control=control);
}

Can be used like this:

png('a.png');hist(rnorm(700));dev.off()
sendMessage('Here you have a nice histogram:',
'Nice picture',
'[email protected]',
'[email protected]',
'image/png',
'a.png',list(smtpServer="..."))

Be warned that message sent by this example will probably be marked as spam, since it is a short text and a big picture -- nevertheless for larger messages and, let's say, pdf attachments it should go through. If not, you may consider adding also a text version of the message.

EDIT (less relevant now): The most deep insight on how to make MIME messages can be found here.

眼眸印温柔 2024-09-23 16:12:58

请注意,当前版本的 sendmailR 通过将 msg 设为 mime_type 对象列表来支持开箱即用的附件,即您现在

sendmail( from,to,subject,
          msg=list(mime_part("Here's an attachment for you!"), 
          mime_part(attachmentFileName)), control, headers)`

Note that current versions of sendmailR support attachments out of the box by making msg a list of mime_type objects, i.e. you'd now

sendmail( from,to,subject,
          msg=list(mime_part("Here's an attachment for you!"), 
          mime_part(attachmentFileName)), control, headers)`
给我一枪 2024-09-23 16:12:58

下面是一个为日常批处理作业设置的示例,例如在 R 中使用 sendmail() 进行设置(可通过 sendmailR 包获得),并带有多个附件(一个 CSV、一个 PDF):

设置要在文件名中引用的日期信息:

> yesterday_date_stuff  <- new.env()
> yesterday_date_stuff[['month']] <- strftime(Sys.Date()-1, format="%m")
> yesterday_date_stuff[['day']] <- strftime(Sys.Date()-1, format="%d")
> yesterday_date_stuff[['year']] <- strftime(Sys.Date()-1, format="%y")
> yesterday_date_stuff$month
[1] "03"
> yesterday_date_stuff$day
[1] "29"
> yesterday_date_stuff$year
[1] "17"

现在创建本文末尾的 sendmail() 函数所需的一些信息:

> from <- "[email protected]"
> to <- c("[email protected]", "[email protected]", "[email protected]")
> subject <- paste("whatever you want subject line to read for batch job analyzing data for ", yesterday_date_stuff$month, "/", yesterday_date_stuff$day, "/", yesterday_date_stuff$year, sep="")
> body <- "Text to insert into the body of your email"                     

在此处指定邮件服务器:

> mailControl=list(smtpServer="mail.whateveryourmailserveris.com")

定义附件 1 路径和名称:

> attachmentPath1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")
> attachmentName1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")

定义附件 1 对象:

> attachmentObject1 <- mime_part(x=attachmentPath1,name=attachmentName1)

定义附件 2 路径和名称:

> attachmentPath2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")
> attachmentName2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")

定义附件 2 对象:

> attachmentObject2 <- mime_part(x=attachmentPath2,name=attachmentName2)

现在合并正文带有附件的电子邮件:

> bodyWithAttachment <- list(body,attachmentObject1, attachmentObject2)
> bodyWithAttachment
[[1]]
[1] "Text to insert into the body of your email"

[[2]]
<environment: 0x000000004efff188>
attr(,"class")
[1] "mime_part"

[[3]]
<environment: 0x00000000407a1b68>
attr(,"class")
[1] "mime_part"

使用 sendmail() 函数发送电子邮件:

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

Here's an example that is setup for a daily batch job like setting using sendmail() in R (available with the package sendmailR) with multiple attachments (one CSV, one PDF):

Setting up date information to reference in the file names:

> yesterday_date_stuff  <- new.env()
> yesterday_date_stuff[['month']] <- strftime(Sys.Date()-1, format="%m")
> yesterday_date_stuff[['day']] <- strftime(Sys.Date()-1, format="%d")
> yesterday_date_stuff[['year']] <- strftime(Sys.Date()-1, format="%y")
> yesterday_date_stuff$month
[1] "03"
> yesterday_date_stuff$day
[1] "29"
> yesterday_date_stuff$year
[1] "17"

Now create some of the needed information for sendmail() function at the end of this post:

> from <- "[email protected]"
> to <- c("[email protected]", "[email protected]", "[email protected]")
> subject <- paste("whatever you want subject line to read for batch job analyzing data for ", yesterday_date_stuff$month, "/", yesterday_date_stuff$day, "/", yesterday_date_stuff$year, sep="")
> body <- "Text to insert into the body of your email"                     

Specify mail server here:

> mailControl=list(smtpServer="mail.whateveryourmailserveris.com")

Define attachment 1 path and name:

> attachmentPath1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")
> attachmentName1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")

Define attachment 1 object:

> attachmentObject1 <- mime_part(x=attachmentPath1,name=attachmentName1)

Define attachment 2 path and name:

> attachmentPath2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")
> attachmentName2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")

Define attachment 2 object:

> attachmentObject2 <- mime_part(x=attachmentPath2,name=attachmentName2)

Now combine the body of the email with your attachments:

> bodyWithAttachment <- list(body,attachmentObject1, attachmentObject2)
> bodyWithAttachment
[[1]]
[1] "Text to insert into the body of your email"

[[2]]
<environment: 0x000000004efff188>
attr(,"class")
[1] "mime_part"

[[3]]
<environment: 0x00000000407a1b68>
attr(,"class")
[1] "mime_part"

Send the email using sendmail() function:

> sendmail(from=from, to=to, subject=subject, msg=bodyWithAttachment, control=mailControl)
咋地 2024-09-23 16:12:58

我会为此放弃使用 R。在 Python 中存在用于执行此操作的有效、跨平台、稳定的解决方案,并且您可以从 R 调用 Python。

如果我必须在 Python 程序中安装混合效果模型,我会调用 R 来执行此操作 - 如果我愿意的话像在 R 中发送电子邮件这样的系统任务我将调用 Python 来完成。如果您还不知道,它值得学习。

I would give up on using R for this. Working, cross-platform, stable solutions for doing this in Python exist, and you can call Python from R.

If I had to fit a mixed effects model in a Python program I'd call R to do it - if I want to do a systems task like send email in R I'll call Python to do it. Its worth learning if you don't know it yet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文