Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send HTML email using R

Tags:

html

email

r

I have searched SO and well as google and cannot seem to find a solution to my problem. I am trying to send a HTML formatted email within R using sendmailR package. The plain text email works just fine, but then am unable to switch from plain text to HTML.

My code:

require(sendmailR)
from <- "[email protected]"
message = "<HTML><body><b>Hello</b></body></HTML>"
to = c("[email protected]")
subject = "Test Monitor Alert"

sendmail(from, to, subject, msg = msg,control=list(smtpServer="smtp-gw1.wal-mart.com"),headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed"))

I do get the email, but its in plain text and the email body contains the message as is instead of the HTML formatted text. Please help.

like image 417
Rohit Das Avatar asked Nov 07 '13 19:11

Rohit Das


3 Answers

This is possible, cf https://stackoverflow.com/a/21930556/448145 Just add:

msg <- mime_part(message)
msg[["headers"]][["Content-Type"]] <- "text/html"
sendmail(from, to, subject, msg = msg, ...)
like image 165
Karl Forner Avatar answered Sep 27 '22 19:09

Karl Forner


sendmailR cannot do this because it is hard-coded to send the message part out as text. If you look at the packages source, line 38 of sendmail.R is the following:

writeLines("Content-Type: text/plain; format=flowed\r\n", sock, sep="\r\n")

Change that to

writeLines("Content-Type: text/html; format=flowed\r\n", sock, sep="\r\n")

like you tried to do through the options and it will work.

Update: sendmailR now allows html emails (see Karl's answer below and https://stackoverflow.com/a/21930556/448145).

like image 36
Christopher Louden Avatar answered Sep 27 '22 17:09

Christopher Louden


With the mailR package (https://github.com/rpremraj/mailR), you could send HTML emails 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)
like image 23
Rahul Premraj Avatar answered Sep 27 '22 18:09

Rahul Premraj