使用Kable生成的表格网格线在mailR邮件中不显示的问题
I’ve run into this exact issue before—mail clients like Gmail or Outlook don’t handle external/embedded CSS (like Bootstrap, which kableExtra’s bordered relies on) nearly as well as web browsers. That’s why your table looks perfect in RStudio Viewer but loses gridlines when sent via email.
The Solution: Inline Your CSS Styles
Mail clients prioritize inline CSS directly attached to HTML elements. We can use kableExtra’s inline_css() function to bake border styles right into the table, headers, and cells so they render consistently across email clients.
Here’s your revised code with this fix:
# Load required packages library(knitr) library(kableExtra) library(dplyr) library(mailR) # Create styled table with inline CSS for email compatibility a <- mtcars[1:10, 1:2] %>% mutate( car = row.names(.), mpg = cell_spec(mpg, "html", color = ifelse(mpg > 20, "red", "blue")), cyl = cell_spec(cyl, "html", color = "white", align = "c", angle = 45, background = factor(cyl, c(4, 6, 8), c("#666666", "#999999", "#BBBBBB"))) ) %>% select(car, mpg, cyl) %>% kable(format = "html", escape = FALSE) %>% kable_styling(bootstrap_options = c("striped", "bordered"), full_width = FALSE) %>% # Add inline CSS to force border rendering in emails inline_css( table_css = "border-collapse: collapse; width: auto;", th_css = "border: 1px solid #ddd; padding: 8px; background-color: #f8f9fa;", td_css = "border: 1px solid #ddd; padding: 8px;" ) # Compose and send email body_B <- paste("<p>", a, "<br><br>Note: report</p>", sep = "") Subject <- paste(Sys.Date(), 'xyz', sep = ":") send.mail( from = "asdf@gmail.com", to = c("asdf@gmail.com"), subject = Subject, body = body_B, html = TRUE, smtp = list( host.name = "smtp.gmail.com", port = 587, user.name = "#####", passwd = "#####", ssl = TRUE ), authenticate = TRUE, send = TRUE )
Key Changes Explained:
inline_css(): This function injects CSS directly into the<table>,<th>, and<td>tags. Theborder-collapse: collapseensures no double borders, while theborder: 1px solid #dddexplicitly defines the gridline style.- Cleaner HTML Body: I adjusted the
body_Bstring to remove unnecessary spaces and add proper line breaks for better readability. - Optional Header Styling: Added a light background to header cells (matches kableExtra’s striped style) to make the table look more polished in emails.
Quick Note on Limitations:
Some email clients (looking at you, Outlook) still struggle with advanced styles like cell rotation (angle=45). If that’s a critical feature, you might need to pre-render the table as an image and attach it instead—but for gridlines and basic color coding, the inline CSS fix should work perfectly.
内容的提问来源于stack exchange,提问作者user9257651

