Im trying to send an email from r using the mailR package. The email is very simple, all I need is for it to display a data.frame in the body of the email.
I am able to send an email using the code below but am struggling to add the data.frame to the body of it.
Here is the code I have used so far:
library(mailR)
sender <- "[email protected]"
recipients <- c("[email protected]")
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()
Any help is much appreciated!
Below is a solution that works for me. You need to convert the data frame into an HTML table using htmlTable
package. See details below.
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 <- "[email protected]"
recipients <- c("[email protected]")
send.mail(from = sender,
to = recipients,
subject = "Test Email",
body = html_body,
smtp = list(host.name = "smtp.gmail.com",
port = 465,
user.name = "[email protected]",
passwd = "PASSWORD",
ssl = TRUE),
authenticate = TRUE,
html = TRUE,
send = TRUE)
Below is how to output looks like in gmail.
If you want a table with borders, use the below code. This uses a little bit of CSS to format the table.
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 <- "[email protected]"
recipients <- c("[email protected]")
send.mail(from = sender,
to = recipients,
subject = "Test Email",
body = html_body,
smtp = list(host.name = "smtp.gmail.com",
port = 465,
user.name = "[email protected]",
passwd = "PASSWORD",
ssl = TRUE),
authenticate = TRUE,
html = TRUE,
send = TRUE)
Below is a screenshot of how the table looks like in gmail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With