Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Add support for embedding images (inline attachments) via CID in campaign bodies (#3034)

Kailash Nadh4f22884244c4
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index c97e5703..07d20ce3 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -643,6 +643,11 @@ func (a *App) GetCampaignViewAnalytics(c echo.Context) error {
// sendTestMessage takes a campaign and a subscriber and sends out a sample campaign message.
func (a *App) sendTestMessage(sub models.Subscriber, camp *models.Campaign) error {
+ if err := a.manager.LoadInlineImages(camp); err != nil {
+ a.log.Printf("error loading inline images: %v", err)
+ return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
+ }
+
if err := camp.CompileTemplate(a.manager.TemplateFuncs(camp)); err != nil {
a.log.Printf("error compiling template: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
diff --git a/cmd/manager_store.go b/cmd/manager_store.go
index 384ad562..d2972939 100644
--- a/cmd/manager_store.go
+++ b/cmd/manager_store.go
@@ -104,6 +104,30 @@ func (s *store) GetAttachment(mediaID int) (models.Attachment, error) {
}, nil
}
+// GetInlineAttachmentByFilename fetches a media item by filename and returns
+// it as an inline attachment along with the Content-ID value. The lookup is
+// uniform across filesystem and S3 providers because both use the same media
+// store interface; the first match for a given filename is returned.
+func (s *store) GetInlineAttachmentByFilename(filename string) (models.Attachment, string, error) {
+ m, err := s.core.GetMedia(0, "", filename, s.media)
+ if err != nil {
+ return models.Attachment{}, "", err
+ }
+
+ b, err := s.media.GetBlob(m.URL)
+ if err != nil {
+ return models.Attachment{}, "", err
+ }
+
+ cid := manager.MakeContentID(m.Filename)
+ return models.Attachment{
+ Name: m.Filename,
+ Content: b,
+ Header: manager.MakeInlineAttachmentHeader(m.Filename, "", m.ContentType, cid),
+ IsInline: true,
+ }, cid, nil
+}
+
// CreateLink registers a URL with a UUID for tracking clicks and returns the UUID.
func (s *store) CreateLink(url string) (string, error) {
// Create a new UUID for the URL. If the URL already exists in the DB
diff --git a/cmd/tx.go b/cmd/tx.go
index 2468b23e..eb545b16 100644
--- a/cmd/tx.go
+++ b/cmd/tx.go
@@ -146,11 +146,13 @@ func (a *App) SendTxMessage(c echo.Context) error {
msg.AltBody = []byte(m.AltBody)
for _, a := range m.Attachments {
msg.Attachments = append(msg.Attachments, models.Attachment{
- Name: a.Name,
- Header: a.Header,
- Content: a.Content,
+ Name: a.Name,
+ Header: a.Header,
+ Content: a.Content,
+ IsInline: a.IsInline,
})
}
+ msg.Attachments = append(msg.Attachments, tpl.Attachments...)
// Optional headers.
if len(m.Headers) != 0 {
diff --git a/frontend/email-builder/src/App/InspectorDrawer/ConfigurationPanel/input-panels/ImageSidebarPanel.tsx b/frontend/email-builder/src/App/InspectorDrawer/ConfigurationPanel/input-panels/ImageSidebarPanel.tsx
index 8193885c..f93002be 100644
--- a/frontend/email-builder/src/App/InspectorDrawer/ConfigurationPanel/input-panels/ImageSidebarPanel.tsx
+++ b/frontend/email-builder/src/App/InspectorDrawer/ConfigurationPanel/input-panels/ImageSidebarPanel.tsx
@@ -1,13 +1,14 @@
-import React, { useState } from 'react';
-import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import {
VerticalAlignBottomOutlined,
VerticalAlignCenterOutlined,
VerticalAlignTopOutlined,
} from '@mui/icons-material';
-import { Stack, ToggleButton } from '@mui/material';
-import { ImageProps, ImagePropsSchema } from '@usewaypoint/block-image';
+import CloudUploadIcon from '@mui/icons-material/CloudUpload';
+import { Checkbox, FormControlLabel, Stack, ToggleButton } from '@mui/material';
+import { ImageProps } from '@usewaypoint/block-image';
+import React, { useState } from 'react';
+import { ImgPropsSchema, ListmonkImageProps } from '../../../../documents/editor/core';
import BaseSidebarPanel from './helpers/BaseSidebarPanel';
import RadioGroupInput from './helpers/inputs/RadioGroupInput';
import TextDimensionInput from './helpers/inputs/TextDimensionInput';
@@ -22,15 +23,17 @@ export default function ImageSidebarPanel({ data, setData }: ImageSidebarPanelPr
const [, setErrors] = useState<Zod.ZodError | null>(null);
const updateData = (d: unknown) => {
- const res = ImagePropsSchema.safeParse(d);
+ const res = ImgPropsSchema.safeParse(d);
if (res.success) {
- setData(res.data);
+ setData(res.data as ImageProps);
setErrors(null);
} else {
setErrors(res.error);
}
};
+ const props = (data && (data as ListmonkImageProps).props) || {};
+
return (
<BaseSidebarPanel title="Image block">
<TextInput
@@ -92,6 +95,17 @@ export default function ImageSidebarPanel({ data, setData }: ImageSidebarPanelPr
</ToggleButton>
</RadioGroupInput>
+ <FormControlLabel
+ control={
+ <Checkbox
+ size="small"
+ checked={Boolean(props.embed)}
+ onChange={(e) => updateData({ ...data, props: { ...data.props, embed: e.target.checked } })}
+ />
+ }
+ label="Embed inline (CID)"
+ />
+
<MultiStylePropertyPanel
names={['backgroundColor', 'textAlign', 'padding']}
value={data.style}
diff --git a/frontend/email-builder/src/documents/editor/core.tsx b/frontend/email-builder/src/documents/editor/core.tsx
index 4db26f17..1cff7796 100644
--- a/frontend/email-builder/src/documents/editor/core.tsx
+++ b/frontend/email-builder/src/documents/editor/core.tsx
@@ -23,6 +23,22 @@ import EmailLayoutEditor from '../blocks/EmailLayout/EmailLayoutEditor';
import EmailLayoutPropsSchema from '../blocks/EmailLayout/EmailLayoutPropsSchema';
import EditorBlockWrapper from '../blocks/helpers/block-wrappers/EditorBlockWrapper';
+// Adds an opt-in `embed` flag to the upstream Image props. The renderer
+// (frontend/email-builder/src/utils.tsx) re-tags marked <img>s with
+// `data-embed` and the backend resolves the src filename to a media item.
+export const ImgPropsSchema = ImagePropsSchema.extend({
+ props: z.object({
+ width: z.number().nullable().optional(),
+ height: z.number().nullable().optional(),
+ url: z.string().nullable().optional(),
+ alt: z.string().nullable().optional(),
+ linkHref: z.string().nullable().optional(),
+ contentAlignment: z.enum(['top', 'middle', 'bottom']).nullable().optional(),
+ embed: z.boolean().nullable().optional(),
+ }).nullable().optional(),
+});
+export type ListmonkImageProps = z.infer<typeof ImgPropsSchema>;
+
const EDITOR_DICTIONARY = buildBlockConfigurationDictionary({
Avatar: {
schema: AvatarPropsSchema,
@@ -73,7 +89,7 @@ const EDITOR_DICTIONARY = buildBlockConfigurationDictionary({
),
},
Image: {
- schema: ImagePropsSchema,
+ schema: ImgPropsSchema,
Component: (data) => {
const props = {
...data,
diff --git a/frontend/email-builder/src/utils.tsx b/frontend/email-builder/src/utils.tsx
index a149c9c1..c57a2966 100644
--- a/frontend/email-builder/src/utils.tsx
+++ b/frontend/email-builder/src/utils.tsx
@@ -4,6 +4,13 @@ import { postProcessForOutlook } from './outlook';
const VIEWPORT_META = '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
const MSO_DOCUMENT_SETTINGS = '<!--[if mso]><noscript><xml xmlns:o="urn:schemas-microsoft-com:office:office"><o:OfficeDocumentSettings><o:AllowPNG/><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript><![endif]-->';
+const HTML_ATTRIBUTE_ESCAPES: Record<string, string> = {
+ '&': '&amp;',
+ '"': '&quot;',
+ "'": '&#x27;',
+ '<': '&lt;',
+ '>': '&gt;',
+};
function injectHeadContents(html: string, contents: string) {
const headMatch = html.match(/<head\b([^>]*)>/i);
@@ -19,13 +26,57 @@ function injectHeadContents(html: string, contents: string) {
return `<head>${contents}</head>${html}`;
}
+function collectImageEmbedURLs(document: TEditorConfiguration): string[] {
+ // The upstream renderer strips the custom `embed` prop before rendering, so
+ // collect URLs from blocks marked for embedding and re-tag the matching <img>
+ // with a `data-embed` flag after rendering. The backend resolves the src
+ // filename to a media item at compile time.
+ const embedURLs: string[] = [];
+
+ for (const block of Object.values(document)) {
+ if (!block || (block as { type?: string }).type !== 'Image') {
+ continue;
+ }
+
+ const props = ((block as { data?: { props?: { url?: string; embed?: boolean } } }).data || {}).props || {};
+ if (props.embed && props.url) {
+ embedURLs.push(props.url);
+ }
+ }
+
+ return embedURLs;
+}
+
+function applyImageEmbeds(html: string, embedURLs: string[]): string {
+ let output = html;
+
+ for (const url of embedURLs) {
+ const re = new RegExp(`<img\\b[^>]*?\\ssrc="${escapeRegExp(escapeHtmlAttribute(url))}"[^>]*>`, 'g');
+ output = output.replace(re, (tag) => (
+ /\bdata-embed\b/.test(tag) ? tag : tag.replace(/(\ssrc="[^"]*")/, '$1 data-embed="true"')
+ ));
+ }
+
+ return output;
+}
+
export function renderHtmlWithMeta(
document: TEditorConfiguration,
options: { rootBlockId: string; outlook?: boolean }
): string {
+ const embedURLs = collectImageEmbedURLs(document);
const html = renderToStaticMarkup(document, options);
- const output = options.outlook ? postProcessForOutlook(html) : html;
+ const rendered = options.outlook ? postProcessForOutlook(html) : html;
+ const output = applyImageEmbeds(rendered, embedURLs);
const head = options.outlook ? `${VIEWPORT_META}${MSO_DOCUMENT_SETTINGS}` : VIEWPORT_META;
return injectHeadContents(output, head);
}
+
+function escapeRegExp(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function escapeHtmlAttribute(s: string): string {
+ return s.replace(/[&"'<>]/g, (ch) => HTML_ATTRIBUTE_ESCAPES[ch]);
+}
diff --git a/frontend/src/components/RichtextEditor.vue b/frontend/src/components/RichtextEditor.vue
index e9ccf234..07220ab2 100644
--- a/frontend/src/components/RichtextEditor.vue
+++ b/frontend/src/components/RichtextEditor.vue
@@ -84,8 +84,8 @@ import 'tinymce/skins/ui/oxide/skin.css';
import 'tinymce/themes/silver';
import { colors, uris } from '../constants';
-import CodeEditor from './CodeEditor.vue';
import Media from '../views/Media.vue';
+import CodeEditor from './CodeEditor.vue';
// Map of listmonk language codes to corresponding TinyMCE language files.
const LANGS = {
@@ -101,6 +101,10 @@ const LANGS = {
tr: 'tr',
};
+const TRACK_LINK = 'trackLink';
+const TRACK_SUFFIX = '@TrackLink';
+const EMBED_IMAGE = 'embedImage';
+
export default {
components: {
Media,
@@ -125,7 +129,6 @@ export default {
isRichtextSourceVisible: false,
isInsertHTMLVisible: false,
insertHTMLSnippet: '',
- isTrackLink: false,
richtextConf: {},
richTextSourceBody: '',
contentType: '',
@@ -176,6 +179,9 @@ export default {
toolbar_sticky: true,
entity_encoding: 'raw',
convert_urls: true,
+ relative_urls: false,
+ remove_script_host: false,
+ extended_valid_elements: 'img[*]',
plugins: [
'anchor', 'autoresize', 'autolink', 'charmap', 'emoticons', 'fullscreen',
'help', 'hr', 'image', 'imagetools', 'link', 'lists', 'paste', 'searchreplace',
@@ -219,13 +225,7 @@ export default {
},
onEditorURLConvert(url) {
- let u = url;
- if (this.isTrackLink && /^https?:\/\//i.test(u)) {
- u = `${u}@TrackLink`;
- }
-
- this.isTrackLink = false;
- return u;
+ return url;
},
onRichtextViewSource() {
@@ -261,69 +261,88 @@ export default {
onEditorDialogOpen(editor) {
const ed = editor;
const oldEd = ed.windowManager.open;
- const self = this;
ed.windowManager.open = (t, r) => {
- const isOK = t.initialData && 'url' in t.initialData && 'anchor' in t.initialData;
+ const data = t.initialData || {};
+ const isLink = data.url && 'anchor' in data;
+ const isImage = data.src && !isLink;
- // Not the link modal.
- if (!isOK) {
- return oldEd.apply(this, [t, r]);
+ if (!isLink && !isImage) {
+ return oldEd.call(ed.windowManager, t, r);
}
- // If an existing link is being edited, check for the tracking flag `@TrackLink` at the end
- // of the url. Remove that from the URL and instead check the checkbox.
- // Default to the last user choice (stored in localStorage), or false if not set.
- let checked = JSON.parse(localStorage.getItem('trackLink') || 'false');
-
- // Check if this is an existing link being edited
- if (t.initialData.url && t.initialData.url.value && t.initialData.url.value !== '') {
- const t2 = t;
- const url = t2.initialData.url.value.replace(/@TrackLink$/, '');
-
- if (t2.initialData.url.value !== url) {
- // Link has @TrackLink suffix - keep it checked
- t2.initialData.url.value = url;
- checked = true;
- } else {
- // Link doesn't have @TrackLink suffix - uncheck it
- checked = false;
- }
+ const { onSubmit } = t;
+ const checkbox = isLink ? { type: 'checkbox', name: TRACK_LINK, label: 'Track link?' } : { type: 'checkbox', name: EMBED_IMAGE, label: this.$t('media.embed') };
+ const spec = { ...t, body: this.withDialogCheckbox(t.body, checkbox) };
+
+ if (isLink) {
+ const cleanURL = (data.url.value || '').replace(/@TrackLink$/, '');
+ const checked = data.url.value !== cleanURL
+ || (!cleanURL && JSON.parse(localStorage.getItem(TRACK_LINK) || 'false'));
+ spec.initialData = { ...data, [TRACK_LINK]: checked, url: { ...data.url, value: cleanURL } };
+ spec.onSubmit = (api) => {
+ const d = api.getData();
+ const shouldTrack = Boolean(d[TRACK_LINK]);
+ const url = (d.url.value || '').replace(/@TrackLink$/, '');
+ localStorage.setItem(TRACK_LINK, JSON.stringify(shouldTrack));
+ if (shouldTrack && /^https?:\/\//i.test(url)) {
+ api.setData({ url: { ...d.url, value: `${url}${TRACK_SUFFIX}` } });
+ }
+ onSubmit(api);
+ };
+ } else {
+ const img = this.getSelectedImage(ed);
+ spec.initialData = { ...data, [EMBED_IMAGE]: Boolean(img && img.hasAttribute('data-embed')) };
+ spec.onSubmit = (api) => {
+ const d = api.getData();
+ const shouldEmbed = d[EMBED_IMAGE] === true || d[EMBED_IMAGE] === 'true';
+
+ onSubmit(api);
+
+ // Apply 'embed' attr.
+ const node = (img && ed.getBody().contains(img)) ? img : this.getSelectedImage(ed);
+ if (!node) {
+ return;
+ }
+ if (shouldEmbed) {
+ ed.dom.setAttrib(node, 'data-embed', 'true');
+ } else {
+ node.removeAttribute('data-embed');
+ }
+ ed.fire('change');
+ ed.save();
+ this.computedValue = ed.getContent();
+ };
}
- // Execute the modal.
- const modal = oldEd.apply(this, [t, r]);
-
- // Is it the link dialog?
- if (isOK) {
- // Insert tracking checkbox.
- const c = document.createElement('input');
- c.setAttribute('type', 'checkbox');
-
- if (checked) {
- c.setAttribute('checked', checked);
- // CRITICAL FIX: Sync the Vue instance state with the checkbox state
- // This ensures that when the checkbox appears checked, the tracking
- // will actually work when the user saves without manually toggling.
- self.isTrackLink = true;
- }
-
- // Store the checkbox's state in the Vue instance to pick up from
- // the TinyMCE link conversion callback.
- c.onchange = (e) => {
- self.isTrackLink = e.target.checked;
- localStorage.setItem('trackLink', JSON.stringify(e.target.checked));
- };
+ return oldEd.call(ed.windowManager, spec, r);
+ };
+ },
- const l = document.createElement('label');
- l.appendChild(c);
- l.appendChild(document.createTextNode('Track link?'));
- l.classList.add('tox-label', 'tox-track-link');
+ withDialogCheckbox(body, checkbox) {
+ if (body.type === 'tabpanel') {
+ return {
+ ...body,
+ tabs: body.tabs.map((tab) => (
+ tab.name === 'general' || tab.title === 'General'
+ ? { ...tab, items: [...tab.items, checkbox] }
+ : tab
+ )),
+ };
+ }
+ return { ...body, items: [...body.items, checkbox] };
+ },
- document.querySelector('.tox-form__controls-h-stack .tox-control-wrap').appendChild(l);
- }
- return modal;
- };
+ getSelectedImage(editor) {
+ const node = editor.selection.getNode();
+ if (!node) {
+ return null;
+ }
+ if (node.nodeName === 'IMG') {
+ return node;
+ }
+ const figure = editor.dom.getParent(node, 'figure.image');
+ return figure ? figure.querySelector('img') : null;
},
onMediaSelect(media) {
@@ -332,7 +351,7 @@ export default {
beautifyHTML(str) {
// Pad all tags with linebreaks.
- let s = this.trimLines(str.replace(/(<(?!(\/)?a|span)([^>]+)>)/ig, '\n$1\n'), true);
+ let s = this.trimLines(str.replace(/(<(?!(\/)?a|span)([^>]+)>)/gi, '\n$1\n'), true);
// Remove extra linebreaks.
s = s.replace(/\n+/g, '\n');
diff --git a/go.mod b/go.mod
index 15423d5d..6fafdff5 100644
--- a/go.mod
+++ b/go.mod
@@ -24,7 +24,7 @@ require (
github.com/knadh/koanf/providers/rawbytes v1.0.0
github.com/knadh/koanf/v2 v2.2.2
github.com/knadh/paginator v1.0.1
- github.com/knadh/smtppool/v2 v2.1.0
+ github.com/knadh/smtppool/v2 v2.1.2
github.com/knadh/stuffbin v1.3.0
github.com/labstack/echo/v4 v4.13.4
github.com/lib/pq v1.10.9
diff --git a/go.sum b/go.sum
index a0511f3b..c4acc397 100644
--- a/go.sum
+++ b/go.sum
@@ -74,8 +74,8 @@ github.com/knadh/koanf/v2 v2.2.2 h1:ghbduIkpFui3L587wavneC9e3WIliCgiCgdxYO/wd7A=
github.com/knadh/koanf/v2 v2.2.2/go.mod h1:abWQc0cBXLSF/PSOMCB/SK+T13NXDsPvOksbpi5e/9Q=
github.com/knadh/paginator v1.0.1 h1:mzbhjx167qRpvv9ym7BBaaNa1//qXU2YKk7mTmSmW9o=
github.com/knadh/paginator v1.0.1/go.mod h1:NDzJofYUQiHbDrWukKRi3E2vIKb0dzOZKY8VmxbM2Sk=
-github.com/knadh/smtppool/v2 v2.1.0 h1:QwtqFQj/DI3gYoLWDg13x2r4tYUbT6F+sAMpgd/m9Gc=
-github.com/knadh/smtppool/v2 v2.1.0/go.mod h1:D7HcfSS8Xd3jpZ9LRwQ3aGdqp9FzFE66uW6w/BTpy4E=
+github.com/knadh/smtppool/v2 v2.1.2 h1:FBpwnDTKmWwUy1reeeMeYJXl2QbUgVsKhAGVgJF3F2I=
+github.com/knadh/smtppool/v2 v2.1.2/go.mod h1:D7HcfSS8Xd3jpZ9LRwQ3aGdqp9FzFE66uW6w/BTpy4E=
github.com/knadh/stuffbin v1.3.0 h1:HaVSuYV+KnrlCHl7DrLNyOCgpTU2K8x5Hb+J4Ck3gww=
github.com/knadh/stuffbin v1.3.0/go.mod h1:yVCFaWaKPubSNibBsTAJ939q2ABHudJQxRWZWV5yh+4=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
diff --git a/i18n/en.json b/i18n/en.json
index 3b1fc344..f39a035f 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -310,6 +310,8 @@
"maintenance.orphanHelp": "Orphans = subscribers with no lists",
"maintenance.title": "Maintenance",
"maintenance.unconfirmedSubs": "Unconfirmed subscriptions older than {name} days.",
+ "media.embed": "Embed inline",
+ "media.embedHelp": "Embed the image in the email as an attachment.",
"media.errorReadingFile": "Error reading file: {error}",
"media.errorResizing": "Error resizing image: {error}",
"media.errorSavingThumbnail": "Error saving thumbnail: {error}",
diff --git a/internal/manager/manager.go b/internal/manager/manager.go
index dc8a65d2..643187b1 100644
--- a/internal/manager/manager.go
+++ b/internal/manager/manager.go
@@ -1,11 +1,16 @@
package manager
import (
+ "crypto/sha1"
+ "encoding/hex"
"errors"
"fmt"
"html/template"
"log"
"net/textproto"
+ "net/url"
+ "path"
+ "regexp"
"strings"
"sync"
"time"
@@ -20,6 +25,15 @@ import (
"golang.org/x/text/language"
)
+// attribInlineEmbed is the HTML attrib used to mark <img> tags whose source
+// should be embedded as a multipart cid inline attachment.
+const attribInlineEmbed = "data-embed"
+
+var (
+ reInlineImage = regexp.MustCompile(`(?is)<img\b[^>]*\b` + attribInlineEmbed + `\b[^>]*>`)
+ reImgSrc = regexp.MustCompile(`(?is)(\s)src\s*=\s*(?:"([^"]*)"|'([^']*)')`)
+)
+
const (
// BaseTPL is the name of the base template.
BaseTPL = "base"
@@ -37,6 +51,7 @@ type Store interface {
NextSubscribers(campID, limit int) ([]models.Subscriber, error)
GetCampaign(campID int) (*models.Campaign, error)
GetAttachment(mediaID int) (models.Attachment, error)
+ GetInlineAttachmentByFilename(filename string) (models.Attachment, string, error)
UpdateCampaignStatus(campID int, status string) error
UpdateCampaignCounts(campID int, toSend int, sent int, lastSubID int) error
CreateLink(url string) (string, error)
@@ -317,6 +332,15 @@ func (m *Manager) Run() {
// CacheTpl caches a template for ad-hoc use. This is currently only used by tx templates.
func (m *Manager) CacheTpl(id int, tpl *models.Template) {
+ if body, atts := m.ApplyInlineImages(tpl.Body); len(atts) > 0 {
+ tpl.Body = body
+ tpl.Attachments = atts
+ if err := tpl.Compile(m.GenericTemplateFuncs()); err != nil {
+ m.log.Printf("error recompiling tx template %d after inline image: %v", id, err)
+ return
+ }
+ }
+
m.tplsMut.Lock()
m.tpls[id] = tpl
m.tplsMut.Unlock()
@@ -659,29 +683,121 @@ func (m *Manager) makeGnericFuncMap() template.FuncMap {
}
// attachMedia loads any media/attachments from the media store and attaches
-// the byte blobs to the campaign.
+// the byte blobs to the campaign. Inline attachments are skipped as they're
+// loaded earlier by LoadInlineImages().
func (m *Manager) attachMedia(c *models.Campaign) error {
- if len(c.Attachments) > 0 {
- return nil
+ // Already loaded if any non-inline attachment is present.
+ for _, a := range c.Attachments {
+ if !a.IsInline {
+ return nil
+ }
}
- // Load any media/attachments.
for _, mid := range []int64(c.MediaIDs) {
a, err := m.store.GetAttachment(int(mid))
if err != nil {
return fmt.Errorf("error fetching attachment %d on campaign %s: %v", mid, c.Name, err)
}
-
c.Attachments = append(c.Attachments, a)
}
return nil
}
-// MakeAttachmentHeader is a helper function that returns a
-// textproto.MIMEHeader tailored for attachments, primarily
-// email. If no encoding is given, base64 is assumed.
+// LoadInlineImages resolves any <img ... data-embed ...> tags in the campaign
+// body and template body one time before CompileTemplate.
+func (m *Manager) LoadInlineImages(c *models.Campaign) error {
+ if c.ContentType == models.CampaignContentTypePlain {
+ return nil
+ }
+
+ cidCache := make(map[string]string)
+ body, atts := m.applyInlineImages(c.Body, cidCache)
+ c.Body = body
+
+ tplBody, tplAtts := m.applyInlineImages(c.TemplateBody, cidCache)
+ c.TemplateBody = tplBody
+ atts = append(atts, tplAtts...)
+
+ c.Attachments = append(c.Attachments, atts...)
+ return nil
+}
+
+// ApplyInlineImages scans body for <img ... data-embed ...> tags, resolves
+// each unique src filename to a media item, attaches it as an inline part, and
+// rewrites the matched img src to cid.
+func (m *Manager) ApplyInlineImages(body string) (string, []models.Attachment) {
+ return m.applyInlineImages(body, make(map[string]string))
+}
+
+func (m *Manager) applyInlineImages(body string, cache map[string]string) (string, []models.Attachment) {
+ if !strings.Contains(body, attribInlineEmbed) {
+ return body, nil
+ }
+
+ var atts []models.Attachment
+ out := reInlineImage.ReplaceAllStringFunc(body, func(tag string) string {
+ src := extractSrc(tag)
+ if src == "" || strings.HasPrefix(strings.ToLower(src), "cid:") {
+ return tag
+ }
+
+ fname := filenameFromSrc(src)
+ if fname == "" {
+ return tag
+ }
+
+ cid, ok := cache[src]
+ if !ok {
+ if a, c, err := m.store.GetInlineAttachmentByFilename(fname); err == nil {
+ atts = append(atts, a)
+ cid = c
+ } else {
+ m.log.Printf("inline image %q not embedded: %v", src, err)
+ }
+ cache[src] = cid
+ }
+ if cid == "" {
+ return tag
+ }
+ return reImgSrc.ReplaceAllString(tag, `${1}src="cid:`+cid+`"`)
+ })
+
+ return out, atts
+}
+
+// MakeContentID returns a standard `Content-ID` value (without the angle brackets).
+func MakeContentID(key string) string {
+ sum := sha1.Sum([]byte(key))
+ return hex.EncodeToString(sum[:8]) + "@email"
+}
+
+// filenameFromSrc extracts a media filename from an <img src> value (ignoring
+// any URLs and just capturing the filename.
+func filenameFromSrc(src string) string {
+ if src == "" {
+ return ""
+ }
+ p := src
+ if u, err := url.Parse(src); err == nil && u.Path != "" {
+ p = u.Path
+ }
+ return path.Base(p)
+}
+
+// MakeAttachmentHeader returns a textproto.MIMEHeader for an email
+// attachment. Default encoding is base64 and contentType is application/octet-stream.
func MakeAttachmentHeader(filename, encoding, contentType string) textproto.MIMEHeader {
+ return makeAttachmentHeader("attachment", filename, encoding, contentType, "")
+}
+
+// MakeInlineAttachmentHeader returns a textproto.MIMEHeader for an inline
+// image attachment referenced from the HTML body via a cid URL.
+func MakeInlineAttachmentHeader(filename, encoding, contentType, contentID string) textproto.MIMEHeader {
+ return makeAttachmentHeader("inline", filename, encoding, contentType, contentID)
+}
+
+func makeAttachmentHeader(disposition, filename, encoding, contentType, contentID string) textproto.MIMEHeader {
if encoding == "" {
encoding = "base64"
}
@@ -690,8 +806,22 @@ func MakeAttachmentHeader(filename, encoding, contentType string) textproto.MIME
}
h := textproto.MIMEHeader{}
- h.Set("Content-Disposition", "attachment; filename="+filename)
+ h.Set("Content-Disposition", disposition+"; filename="+filename)
h.Set("Content-Type", fmt.Sprintf("%s; name=\""+filename+"\"", contentType))
h.Set("Content-Transfer-Encoding", encoding)
+ if contentID != "" {
+ h.Set("Content-ID", "<"+contentID+">")
+ }
return h
}
+
+func extractSrc(tag string) string {
+ m := reImgSrc.FindStringSubmatch(tag)
+ if len(m) == 0 {
+ return ""
+ }
+ if m[2] != "" {
+ return m[2]
+ }
+ return m[3]
+}
diff --git a/internal/manager/pipe.go b/internal/manager/pipe.go
index 69ad8b9e..3b4dafef 100644
--- a/internal/manager/pipe.go
+++ b/internal/manager/pipe.go
@@ -31,6 +31,11 @@ func (m *Manager) newPipe(c *models.Campaign) (*pipe, error) {
return nil, fmt.Errorf("unknown messenger %s on campaign %s", c.Messenger, c.Name)
}
+ // Resolve any inline images before compiling the template.
+ if err := m.LoadInlineImages(c); err != nil {
+ return nil, err
+ }
+
// Load the template.
if err := c.CompileTemplate(m.TemplateFuncs(c)); err != nil {
return nil, err
diff --git a/internal/messenger/email/email.go b/internal/messenger/email/email.go
index 9b3f6398..b86d515c 100644
--- a/internal/messenger/email/email.go
+++ b/internal/messenger/email/email.go
@@ -146,9 +146,10 @@ func (e *Emailer) Push(m models.Message) error {
files = make([]smtppool.Attachment, 0, len(m.Attachments))
for _, f := range m.Attachments {
a := smtppool.Attachment{
- Filename: f.Name,
- Header: f.Header,
- Content: make([]byte, len(f.Content)),
+ Filename: f.Name,
+ Header: f.Header,
+ Content: make([]byte, len(f.Content)),
+ HTMLRelated: f.IsInline,
}
copy(a.Content, f.Content)
files = append(files, a)
diff --git a/models/messages.go b/models/messages.go
index 7914dde5..5dad966e 100644
--- a/models/messages.go
+++ b/models/messages.go
@@ -34,6 +34,10 @@ type Attachment struct {
Name string
Header textproto.MIMEHeader
Content []byte
+
+ // IsInline marks the attachment as an inline (CID) part
+ // to be wrapped in multipart/related.
+ IsInline bool
}
// TxMessage subscriber modes.
diff --git a/models/templates.go b/models/templates.go
index 7d45f21e..b48009cf 100644
--- a/models/templates.go
+++ b/models/templates.go
@@ -30,8 +30,9 @@ type Template struct {
IsDefault bool `db:"is_default" json:"is_default"`
// Only relevant to tx (transactional) templates.
- SubjectTpl *txttpl.Template `json:"-"`
- Tpl *template.Template `json:"-"`
+ SubjectTpl *txttpl.Template `json:"-"`
+ Tpl *template.Template `json:"-"`
+ Attachments []Attachment `json:"-"`
}
// Compile compiles a template body and subject (only for tx templates) and