sendmailR(Part2):以邮件附件发送文件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (52)

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

library(sendmailR)

from <- "<sendmailR@myserver.mycompany.com>"
to <- c("<someone@mycompany.com>","<anotherone@mycompany.com>")
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")))
提问于
用户回答回答于

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

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

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

send.mail(from = "Sender Name <sender@gmail.com>",
          to = "recipient@gmail.com",
          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)
用户回答回答于

代码:

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',
'from@example.com',
'to@example.com',
'image/png',
'a.png',list(smtpServer="..."))

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励