使用mailR将data.frame添加到电子邮件中

时间:2016-03-09 11:09:00

标签: r

我试图使用mailR包从r发送电子邮件。电子邮件非常简单,我只需要在电子邮件正文中显示data.frame。

我可以使用下面的代码发送电子邮件,但我很难将data.frame添加到它的正文中。

这是我到目前为止使用的代码:

library(mailR)
sender <- "email@gmail.com"
recipients <- c("email@gmail.com")

email <- send.mail(from = sender,
to = recipients,
subject="Subject",
body = "Body",
smtp = list(host.name = "aspmx.l.google.com", port = 25),
authenticate = FALSE,
send = FALSE)

email$send()

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

以下是适用于我的解决方案。您需要使用htmlTable包将数据框转换为HTML表。请参阅下面的详细信息。

library(mailR)
library(htmlTable)

# Create a reproducible data frame
x <- head(mtcars)

# Convert the data frame into an HTML Table
y <- htmlTable(x, rnames = FALSE)

# Define body of email
html_body <- paste0("<p> This is a test email. </p>", y)

# Configure details to send email using mailR
sender <- "SENDER@gmail.com"
recipients <- c("RECEIPENT@gmail.com")

send.mail(from = sender,
          to = recipients,
          subject = "Test Email",
          body = html_body,
          smtp = list(host.name = "smtp.gmail.com",
                      port = 465, 
                      user.name = "USERID@gmail.com",            
                      passwd = "PASSWORD",
                      ssl = TRUE),
          authenticate = TRUE,
          html = TRUE,
          send = TRUE)

下面是如何在gmail中输出。

enter image description here

如果您想要带边框的表格,请使用以下代码。这使用一点CSS来格式化表。

library(mailR)
library(htmlTable)

x <- head(mtcars)
y <- htmlTable(x, rnames = FALSE)

html_body <- paste0("<html><head>
               <style>
               body{font-family:Calibri, sans-serif;}
               table{border-left:1px solid #000000;border-top:1px solid #000000;}
               table th{border-right:1px solid #000000;border-bottom:1px solid #000000;font-size:13px; font-weight:bold; margin: 0px; padding-left: 5px; padding-right: 5px; margin: 0px;}
               table td{border-right:1px solid #000000;border-bottom:1px solid #000000;font-size:13px; font-weight:normal; margin: 0px; padding-left: 5px; padding-right: 5px; margin: 0px;}
               </style>
               </head><body><p> This is a test email. Ignore it.</p>",
               y, 
               "</body></html>")

sender <- "SENDER@gmail.com"
recipients <- c("RECIPIENTS@gmail.com")

send.mail(from = sender,
          to = recipients,
          subject = "Test Email",
          body = html_body,
          smtp = list(host.name = "smtp.gmail.com",
                      port = 465, 
                      user.name = "USERNAME@gmail.com",            
                      passwd = "PASSWORD",
                      ssl = TRUE),
          authenticate = TRUE,
          html = TRUE,
          send = TRUE)

下面是gmail中表格的截图。

enter image description here