簡體   English   中英

如何使用 R 發送 HTML 電子郵件

[英]How to send HTML email using R

我已經搜索過 SO 和谷歌,但似乎無法找到解決我的問題的方法。 我正在嘗試使用 sendmailR 包在 R 中發送 HTML 格式的電子郵件。 純文本電子郵件工作正常,但隨后無法從純文本切換到 HTML。

我的代碼:

require(sendmailR)
from <- "alertbot@companyname.com"
message = "<HTML><body><b>Hello</b></body></HTML>"
to = c("me@companyname.com")
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"))

我確實收到了電子郵件,但它是純文本格式,電子郵件正文包含消息,而不是 HTML 格式的文本。 請幫忙。

這是可能的,參見https://stackoverflow.com/a/21930556/448145只需添加:

msg <- mime_part(message)
msg[["headers"]][["Content-Type"]] <- "text/html"
sendmail(from, to, subject, msg = msg, ...)

sendmailR不能這樣做,因為將消息部分作為文本發送出去是硬編碼的。 如果您查看包源,則 sendmail.R 的第 38 行如下:

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

將其更改為

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

就像你試圖通過選項做的那樣,它會起作用。

更新sendmailR現在允許 html 電子郵件(參見下面 Karl 的回答和https://stackoverflow.com/a/21930556/448145 )。

使用 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)

我更喜歡使用專門的郵件代理來完成此類任務,而不是使用 R 包。 例如,您可以使用Mutt 適用於 linux 和 windows。

在這里,我使用選項 -e 發送命令:

writeLines(message,
           p<-pipe(paste('mutt -e ','"set content_type=text/html"',
                          from,to,' -s ', subject))
close(p)

如果不出意外,您可以將 html 發布到 php 頁面,並讓 php 發送 html 電子郵件。 我們會看看其他人是否有更好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM