mat-sz / react-letter

✉️ Display e-mails in your React.js projects. (Targets Gmail rendering.)
BSD 3-Clause Clear License
265 stars 7 forks source link

A trick to show embedded images from attachments #18

Closed ecarreras closed 2 years ago

ecarreras commented 2 years ago

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']}
    />;
}
mat-sz commented 2 years ago

This is a letterparser issue.

I've added the contentId property for the attachments in 0.0.9 (released today).

timothyarmes commented 1 year ago

That's really helpful, should be part of the docs.