✉️ Display e-mails in your React.js projects. (Targets Gmail rendering.)

Overview

react-letter

workflow npm npm NPM

react-letter is a React.js component that allows for an easy display of HTML e-mail content with automatic sanitization. Support for features should match what is supported by Gmail.

Features:

  • <style> support.
  • Automatic removal of relative URLs.
  • Support for rewriting the link and resource URLs to increase user's privacy and security.
  • Prefixing classes and IDs to prevent clashing with page styles.
  • Wrapping contents in an iframe (as an option).
  • First-class TypeScript support (the entire library is written in TypeScript), along with a related RFC 822 parser project also written in TypeScript.
  • Only one dependency (lettersanitizer).

The component itself is parser-agnostic, and can be used with any RFC 822 parser as long as it provides HTML or text output. The sanitization is done on the client-side using DOMParser with some security features targeting older browsers (although there's no guarantee of full functionality under browser versions older than 5 years).

Check other TypeScript e-mail projects:

Parser Inbound SMTP
letterparser microMTA

Installation

react-letter is available on NPM, and can be installed with either npm or yarn:

yarn add react-letter

A Vue.js version is also available: vue-letter.

Usage

See: Example or play in the CodeSandbox.

react-letter can be used with letterparser (currently in development, but it's the only RFC 822 parser with browser support as far as I know) or any other parser like this:

import { Letter } from 'react-letter';
import { extract } from 'letterparser';

const { html, text } = extract(`Date: Wed, 01 Apr 2020 00:00:00 -0000
From: A <[email protected]>
To: B <[email protected]>
Subject: Hello world!
Mime-Version: 1.0
Content-Type: text/html; charset=utf-8

Some message.`);

// No sanitization needs to be performed beforehand,
// react-letter takes care of sanitizing the input.
<Letter html={html} text={text} />;

Configuration

Letter supports the following properties:

useIframe?: boolean;

Should the HTML be wrapped in an iframe. Default: false.

iframeTitle?: string;

Iframe title, usually set to subject of the message.

rewriteExternalResources?: (url: string) => string;

The result of this function will be used to rewrite the URLs for url(...) in CSS and src attributes in HTML.

rewriteExternalLinks?: (url: string) => string;

The result of this function will be used to rewrite the URLs for href attributes in HTML.

allowedSchemas?: string[];

List of allowed URL schemas. Default: ['http', 'https', 'mailto'].

preserveCssPriority?: boolean;

Preserves CSS priority (!important), default: true.

className?: string;

Class name of the wrapper div.

Comments
  • Link schemes are case sensitive

    Link schemes are case sensitive

    Google docs for example sends urls that look like this: MAILTO:[email protected] which this library strips because the names are case sensitive, we can work around this by adding the difference casings to allowed schemes, but can we make comparison case insensitive?

    bug 
    opened by rockwotj 3
  • Turn sanitizer into an external package?

    Turn sanitizer into an external package?

    Fancy that code, although I do not need the other parts. So how about moving this to an external package for easier reuse?

    Call it email-sanitizer or so? Thanks :)

    enhancement 
    opened by binarykitchen 2
  • Support attachments

    Support attachments

    Thanks for an interesting project (again).

    I notice a closed issue about inline attachments, but I've got an attachment like this:

    Content-Type: image/jpeg; name=chart.jpg
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment; filename=chart.jpg
    

    I'm not seeing that displayed - would you expect it to be?

    wontfix 
    opened by edwh 2
  • Allow deprecated attributes in table tags

    Allow deprecated attributes in table tags

    Especially for older HTML (as is common in emails for example) deprecated/obsolete attributes still seem common for table tags.

    This PR updates the table tags to include the deprecated/obsolete attributes. As far as I can see all of these should be safe to use.

    opened by jdimond 2
  • A trick to show embedded images from attachments

    A trick to show embedded images from attachments

    This is a trick to show images embedded as attachments, it could be better if the attachment had the "Content-Id" header which is unique, but for now we can found it with the name.

    import { Letter } from 'react-letter';
    import { extract } from 'letterparser';
    import { fromByteArray } from 'base64-js';
    
    export default function App() {
    
      const { html, text, attachments } = extract("RAW EMAIL CONTENT");
    
      const rewriteSrc = (url) => {
        if (url.startsWith('cid:')) {
          const image = url.split(':')[1].split('@')[0]
          const imageAtt = attachments.filter(a => a.contentType.parameters.name === image);
          if (imageAtt.length > 0) {
            return `data:${imageAtt[0].contentType.type};base64, ${fromByteArray(imageAtt[0].body)}`
          }
        } else {
          return url;
        }
      }
      return <Letter html={html} text={text}
        rewriteExternalResources={rewriteSrc}
        allowedSchemas={['http', 'https', 'mailto', 'cid']}
        />;
    }
    
    opened by ecarreras 1
  • 100% cpu cost and lagging

    100% cpu cost and lagging

    In production I have issue with this html. If use dangerouslySetInnerHTML, there is no error, but if use react-letter CPU will hold on 100% and the browser will be unresponded Please check error.zip .

    opened by huunghia98 1
  • Add target=

    Add target="_blank" to all links

    as far as you already set them rel="noopener noreferrer" https://github.com/mat-sz/react-letter/issues/4 or at least could you provide the possibility to change this "target" field in links?

    image

    bug 
    opened by Vagizova 1
  • Non HTML namespace elements break sanitize

    Non HTML namespace elements break sanitize

    I was checking to see if this vulnerability in PurifyDOM effected react-letter, and it crashed with this input. Below is the input given:

    <form>
    <math><mtext>
    </form><form>
    <mglyph>
    <style></math><img src onerror=alert(1)>
    

    It seems to crash because math elements don't have a style property.

    bug 
    opened by rockwotj 1
  • Adding computed styles for background-{position,repeat}

    Adding computed styles for background-{position,repeat}

    This updates a couple of the computed styles that were missing. You can test with this:

    <div style="background-image:url('https://mdn.mozillademos.org/files/11987/startransparent.gif');width:100px;height:100px;background-position:center;background-repeat:no-repeat"/>
    

    Chrome reports these properties for that element:

    ["background-image", "width", "height", "background-position-x", "background-position-y", "background-repeat-x", "background-repeat-y"]
    

    Also update the example to be a bit more useable and easy to test against.

    opened by rockwotj 1
Owner
Mat Sz
I'm a web developer (with over 5 years of commercial experience) and an UI/UX designer.
Mat Sz
The easiest way to move your React application to Server-Side Rendering. Handles Side Effects and synchronizes State.

The easiest way to move your React application to Server-Side Rendering. Handles Side Effects and synchronizes State. Table of Contents Articles Featu

Sergey 94 Dec 4, 2022
React Navigation for React js that tries to ensure that the elements of the navigators display correctly on devices with notches and UI elements which may overlap the app content.

React Navigation for React js that tries to ensure that the elements of the navigators display correctly on devices with notches (e.g. iPhone X) and UI elements which may overlap the app content.

MohammadAli Karimi 11 Nov 27, 2022
A website made to display poems as a sharing website and resource for students in Singapore American School

7C Poems This is a website made to display poems as a sharing website and resource for students in Singapore American School. It’s made using React, T

null 1 May 20, 2022
React ESI: Blazing-fast Server-Side Rendering for React and Next.js

React ESI: Blazing-fast Server-Side Rendering for React and Next.js React ESI is a super powerful cache library for vanilla React and Next.js applicat

Kévin Dunglas 632 Dec 29, 2022
HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API.

React Document Meta HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API. Built wi

kodyl 320 Nov 18, 2022
Complete token authentication system for react + redux that supports isomorphic rendering.

Simple, secure authentication for react + redux TL;DR - View the Live Demo You can see a complete working example here. The code for the demo is here.

Lynn Dylan Hurley 2.1k Dec 27, 2022
Adds server side rendering support to React Relay

Isomorphic React Relay Enables server-side rendering of React Relay containers. If you use react-router-relay you might also become interested in isom

Denis Nedelyaev 246 May 22, 2022
Our SDK for the 3D rendering platform React-Three-Fiber.

Zappar for React Three Fiber This library allows you use Zappar's best-in-class AR technology with content built using the 3D rendering platform React

Zappar 36 Dec 28, 2022
Studies about Software Architeture in React - basics of server-side rendering, state management and code splitting

Studies about Software Architeture in React - basics of server-side rendering, state management and code splitting

Jéssica Félix 2 Mar 23, 2022
An interactive CLI automation tool 🛠️ for creating react.js and next.js projects most fast and efficiently. ⚛️

An interactive CLI automation tool ??️ for creating react.js and next.js projects most fast and efficiently. ⚛️

Alexis Guzman 27 Apr 12, 2022
A library that makes using pdfjs in react projects easy.

A library that makes using pdfjs in react projects easy.

Lukas Möller 3 Feb 5, 2022
This is my Portfolio built with React. The app shows information about me, my projects, resume.

Elyor Doniyorov Built With React.js Live demo Netlify Live link Getting Started To get a local copy run the following steps: Copy this link https://gi

ELYOR 2 Jan 21, 2022
This repository contains different React components, hooks, apps and libraries that are used in different projects here at NaN Labs.

This repository contains different React components, hooks, apps and libraries that are used in different projects here at NaN Labs.

NaN Labs 9 Nov 18, 2022
This project is collection of large projects's source code (codebases), built with Reactjs. Eg: Bestbuy, Postman, Trello, Udacity, Coursera, Skillshare, Invision, Intercom, Pipedrive, ... and more.

This project is collection of large projects's source code (codebases), built with Reactjs. Eg: Bestbuy, Postman, Trello, Udacity, Coursera, Skillshare, Invision, Intercom, Pipedrive, ... and more.

null 1.1k Jan 5, 2023
Automatically finds jQuery methods from existing projects and generates vanilla js alternatives.

Automatically find jQuery methods from existing projects and generate vanilla js alternatives.

Sachin Neravath 1.1k Dec 28, 2022
ReactJs Advanced Projects

ReactJs-Advanced-Projects Tech We Used ReactJs Firebase Hosting Firebase Auth Firebase Storage React-Dom React Redux Steps to run in your machine Run

Alan Binu 22 Dec 27, 2022
A React Custom able cursor that can decorate your site also your hand is open to manipulate the cursor with css

custom-react-cursor A React Custom able cursor that can decorate your site also your hand is open to manipulate the cursor with css Demo live Installi

amirhossein 18 Nov 9, 2022
Live coding in your browser with your favourite language.

Live coding in your browser with your favourite language.

Fatih Erikli 986 Nov 20, 2021
LocateJS predicts your location by analyzing your connection and system data.

LocateJS predicts your location by analyzing your connection and system data.

z0ccc 283 Dec 13, 2022