sendgrid / sendgrid-nodejs

The Official Twilio SendGrid Led, Community Driven Node.js API Library
https://sendgrid.com
MIT License
3k stars 782 forks source link

Inline Attachments + Transactional Templates = broken email #1404

Open thexeos opened 4 months ago

thexeos commented 4 months ago

Use case

Sending a transactional email (saved as Dynamic Template in SendGrid) with inlined images (to avoid remote images getting blocked by default on virtually 100% of modern email clients), such as header design, product images, logo in the footer.

Issue

When passing attachments and templateId in one call, the structure of the generated email is spec non-conforming and results in broken email with inline images showing as separate attachments.

sgMail.send({
  to: 'recipient@example.org',
  from: 'sender@example.org',
  subject: 'Hello world',
  text: 'Hello plain world!',
  html: '<p>Hello HTML world! <img src="cid:img2" /></p>',
  templateId: 'd-f43daeeaef504760851f727007e0b5d0',
  dynamic_template_data: {
    subject: 'Testing Templates & Stuff',
    name: 'Some "Testing" One',
    city: '<b>Denver<b>',
  },
  attachments: [
    {
      content: textBuffered.toString('base64'),
      filename: 'img1.jpg',
      type: 'image/jpeg',
      disposition: 'inline',
      content_id: 'img1',
    },
    {
      content: textBuffered.toString('base64'),
      filename: 'img2.jpg',
      type: 'image/jpeg',
      disposition: 'inline',
      content_id: 'img2',
    },
  ],
})

Expected structure

multipart/alternative
├── text/plain
└── multipart/related
    ├── text/html
    ├── image/jpeg (inline image 1)
    └── image/jpeg (inline image 2)

Actual structure

multipart/related
└── multipart/alternative
    ├── text/plain
    └── text/html
├── image/jpeg (inline image 1)
└── image/jpeg (inline image 2)

Known workarounds

Additional comments

Since Transactional Templates don't support inline image attachments (for some reason) it's already inconvenient enough for developers that inline images must be passed via an API parameters. Now with this issue, Transactional Templates completely lose value and it puts developers one step away from constructing their own email and using "pure MTA" service instead.