简体   繁体   中英

HTML e-mail generated by React breaks in GMail web client

I needed to generate a newsletter e-mail server-side. I researched various options, but I picked React (server-side rendering) because of good TypeScript support and my familiarity with that technology.

Generating an e-mail that displays correctly in GMail (or any other popular client) is a very tricky subject, as one needs to use small (and legacy) HTML subset. But that's a separate issue.

So I've crafted a test e-mail with React SSR, using the subset of HTML supported by GMail. To be sure, I've validated it with W3 Validator and it was successfully checked.

But when I sent the generated HTML output to a GMail address and displayed it in the GMail desktop web application, the output was a mess. In the mail HTML presented in the browser, some elements had missing inline CSS properties, while other were outside of their original parents.

How can I generate an e-mail using React that doesn't break in the GMail web application?

React renderToString function (and the similar ones, too, probably) emits a single-line minified HTML output without any line length limit.

For reasons beyond my reasoning, such single-line HTML documents can "break" GMail HTML parser and cause glitchy output.

But, on the other hands, resources online actually recommend e-mail HTML minification, as whitespace can (reportedly) be interpreted inconsistently across e-mail clients. So pretty-printing HTML output doesn't sound like a good idea.

A solution is to re-minify the HTML document, but with a line length limit. To be safe, I've put the limit quite low. I've used a popular html-minifier package.

import * as React from "react";
import { minify } from "html-minifier";
import { renderToString } from "react-dom/server";

export const renderMyMail = (params: MyMailParams): string => {
  const reactHtmlString = renderToString(MyMail({ params }));
  const reminifiedHtmlString = minify(reactHtmlString, { maxLineLength: 255, keepClosingSlash: true });
  return reminifiedHtmlString;
};

Now, the e-mail displays correctly in GMail web application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM