Skip to content

Instantly share code, notes, and snippets.

@albertorestifo
Created April 26, 2017 11:48
Show Gist options
  • Save albertorestifo/6459ed313427d1cc79d226054e731595 to your computer and use it in GitHub Desktop.
Save albertorestifo/6459ed313427d1cc79d226054e731595 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const Path = require('path');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const Email = require('../lib/Email').default;
const STYLE_TAG = '%STYLE%';
const CONTENT_TAG = '%CONTENT%';
/**
* Get the file from a relative path
* @param {String} relativePath
* @return {Promise.<string>}
*/
function getFile(relativePath) {
return new Promise((resolve, reject) => {
const path = Path.join(__dirname, relativePath);
return fs.readFile(path, { encoding: 'utf8' }, (err, file) => {
if (err) return reject(err);
return resolve(file);
})
});
}
/**
* Renders the React app with the passed data.
* Returns a promise that resolves to the full email HTML.
* @param {Object} data
* @return {Promise.<String>}
*/
function createEmail(data) {
return Promise.all([
getFile('../src/inlined.css'),
getFile('./email.html'),
])
.then(([style, template]) => {
const emailElement = React.createElement(Email, { data });
const content = ReactDOMServer.renderToStaticMarkup(emailElement);
// Replace the template tags with the content
let emailHTML = template;
emailHTML = emailHTML.replace(CONTENT_TAG, content);
emailHTML = emailHTML.replace(STYLE_TAG, style);
return emailHTML;
});
}
module.exports = createEmail;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
%STYLE%
</style>
</head>
<body style="width:100% !important; -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%; margin:0; padding:0;">
%CONTENT%
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment