feat: add support for templating the email content
Signed-off-by: Heikki Hellgren <heikki.hellgren@op.fi>
This commit is contained in:
@@ -4,6 +4,42 @@ Adds support for sending Backstage notifications as emails to users.
|
||||
|
||||
Supports sending emails using SMTP, SES, or sendmail.
|
||||
|
||||
## Customizing email content
|
||||
|
||||
The email content can be customized with the `notificationsEmailTemplateExtensionPoint`. When you create
|
||||
this extension, you can set the custom `NotificationTemplateRenderer` to the module. To modify the contents,
|
||||
override the `getSubject`, `getHtml` and `getText` methods.
|
||||
|
||||
```ts
|
||||
import { notificationsEmailTemplateExtensionPoint } from '@backstage/plugin-notifications-backend-module-email';
|
||||
import { Notification } from '@backstage/plugin-notifications-common';
|
||||
|
||||
export const notificationsModuleEmailDecorator = createBackendModule({
|
||||
pluginId: 'notifications',
|
||||
moduleId: 'email.templates',
|
||||
register(reg) {
|
||||
reg.registerInit({
|
||||
deps: {
|
||||
emailTemplates: notificationsEmailTemplateExtensionPoint,
|
||||
},
|
||||
async init({ emailTemplates }) {
|
||||
emailTemplates.setTemplateRenderer({
|
||||
getSubject(notification) {
|
||||
return `New notification from ${notification.source}`;
|
||||
},
|
||||
getText(notification) {
|
||||
return notification.content;
|
||||
},
|
||||
getHtml(notification) {
|
||||
return `<p>${notification.content}</p>`;
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Example configuration:
|
||||
|
||||
```yaml
|
||||
|
||||
@@ -4,8 +4,29 @@
|
||||
|
||||
```ts
|
||||
import { BackendFeature } from '@backstage/backend-plugin-api';
|
||||
import { ExtensionPoint } from '@backstage/backend-plugin-api';
|
||||
import { Notification as Notification_2 } from '@backstage/plugin-notifications-common';
|
||||
|
||||
// @public (undocumented)
|
||||
export interface NotificationsEmailTemplateExtensionPoint {
|
||||
// (undocumented)
|
||||
setTemplateRenderer(renderer: NotificationTemplateRenderer): void;
|
||||
}
|
||||
|
||||
// @public (undocumented)
|
||||
export const notificationsEmailTemplateExtensionPoint: ExtensionPoint<NotificationsEmailTemplateExtensionPoint>;
|
||||
|
||||
// @public (undocumented)
|
||||
const notificationsModuleEmail: () => BackendFeature;
|
||||
export default notificationsModuleEmail;
|
||||
|
||||
// @public (undocumented)
|
||||
export interface NotificationTemplateRenderer {
|
||||
// (undocumented)
|
||||
getHtml?(notification: Notification_2): string;
|
||||
// (undocumented)
|
||||
getSubject?(notification: Notification_2): string;
|
||||
// (undocumented)
|
||||
getText?(notification: Notification_2): string;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -81,10 +81,6 @@ export interface Config {
|
||||
* Sender email address
|
||||
*/
|
||||
sender: string;
|
||||
/**
|
||||
* Email format, defaults to HTML
|
||||
*/
|
||||
format?: 'html' | 'text';
|
||||
/**
|
||||
* Optional reply-to address
|
||||
*/
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
"test": "backstage-cli package test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-ses": "3.554.0",
|
||||
"@aws-sdk/client-ses": "^3.550.0",
|
||||
"@aws-sdk/types": "^3.347.0",
|
||||
"@backstage/backend-common": "workspace:^",
|
||||
"@backstage/backend-plugin-api": "workspace:^",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2024 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { createExtensionPoint } from '@backstage/backend-plugin-api';
|
||||
import { Notification } from '@backstage/plugin-notifications-common';
|
||||
|
||||
/**
|
||||
* @public
|
||||
*/
|
||||
export interface NotificationTemplateRenderer {
|
||||
getSubject?(notification: Notification): string;
|
||||
getText?(notification: Notification): string;
|
||||
getHtml?(notification: Notification): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @public
|
||||
*/
|
||||
export interface NotificationsEmailTemplateExtensionPoint {
|
||||
setTemplateRenderer(renderer: NotificationTemplateRenderer): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* @public
|
||||
*/
|
||||
export const notificationsEmailTemplateExtensionPoint =
|
||||
createExtensionPoint<NotificationsEmailTemplateExtensionPoint>({
|
||||
id: 'notifications.email.templates',
|
||||
});
|
||||
@@ -21,3 +21,4 @@
|
||||
*/
|
||||
|
||||
export { notificationsModuleEmail as default } from './module';
|
||||
export * from './extensions';
|
||||
|
||||
@@ -20,6 +20,10 @@ import {
|
||||
import { CatalogClient } from '@backstage/catalog-client';
|
||||
import { notificationsProcessingExtensionPoint } from '@backstage/plugin-notifications-node';
|
||||
import { NotificationsEmailProcessor } from './processor';
|
||||
import {
|
||||
notificationsEmailTemplateExtensionPoint,
|
||||
NotificationTemplateRenderer,
|
||||
} from './extensions';
|
||||
|
||||
/**
|
||||
* @public
|
||||
@@ -28,6 +32,16 @@ export const notificationsModuleEmail = createBackendModule({
|
||||
pluginId: 'notifications',
|
||||
moduleId: 'email',
|
||||
register(reg) {
|
||||
let templateRenderer: NotificationTemplateRenderer | undefined;
|
||||
reg.registerExtensionPoint(notificationsEmailTemplateExtensionPoint, {
|
||||
setTemplateRenderer(renderer) {
|
||||
if (templateRenderer) {
|
||||
throw new Error(`Email template renderer was already registered`);
|
||||
}
|
||||
templateRenderer = renderer;
|
||||
},
|
||||
});
|
||||
|
||||
reg.registerInit({
|
||||
deps: {
|
||||
config: coreServices.rootConfig,
|
||||
@@ -49,6 +63,7 @@ export const notificationsModuleEmail = createBackendModule({
|
||||
catalogClient,
|
||||
auth,
|
||||
cache,
|
||||
templateRenderer,
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
+3
-3
@@ -213,7 +213,7 @@ describe('NotificationsEmailProcessor', () => {
|
||||
html: '<p></p>',
|
||||
replyTo: undefined,
|
||||
subject: 'notification',
|
||||
text: undefined,
|
||||
text: '',
|
||||
to: 'mock@backstage.io',
|
||||
});
|
||||
});
|
||||
@@ -271,7 +271,7 @@ describe('NotificationsEmailProcessor', () => {
|
||||
html: '<p></p>',
|
||||
replyTo: undefined,
|
||||
subject: 'notification',
|
||||
text: undefined,
|
||||
text: '',
|
||||
to: 'mock@backstage.io',
|
||||
});
|
||||
});
|
||||
@@ -330,7 +330,7 @@ describe('NotificationsEmailProcessor', () => {
|
||||
html: '<p></p>',
|
||||
replyTo: undefined,
|
||||
subject: 'notification',
|
||||
text: undefined,
|
||||
text: '',
|
||||
to: 'broadcast@backstage.io',
|
||||
});
|
||||
});
|
||||
|
||||
+55
-28
@@ -34,12 +34,12 @@ import { createSesTransport } from './transports/ses';
|
||||
import { UserEntity } from '@backstage/catalog-model';
|
||||
import { compact } from 'lodash';
|
||||
import { DefaultAwsCredentialsManager } from '@backstage/integration-aws-node';
|
||||
import { NotificationTemplateRenderer } from '../extensions';
|
||||
|
||||
export class NotificationsEmailProcessor implements NotificationProcessor {
|
||||
private transporter: any;
|
||||
private readonly broadcastConfig?: Config;
|
||||
private readonly sender: string;
|
||||
private readonly format: string;
|
||||
private readonly replyTo?: string;
|
||||
private readonly cacheTtl: number;
|
||||
|
||||
@@ -49,13 +49,12 @@ export class NotificationsEmailProcessor implements NotificationProcessor {
|
||||
private readonly catalog: CatalogClient,
|
||||
private readonly auth: AuthService,
|
||||
private readonly cache?: CacheService,
|
||||
private readonly templateRenderer?: NotificationTemplateRenderer,
|
||||
) {
|
||||
this.broadcastConfig = config.getOptionalConfig(
|
||||
'notifications.email.broadcastConfig',
|
||||
);
|
||||
this.sender = config.getString('notifications.email.sender');
|
||||
this.format =
|
||||
config.getOptionalString('notifications.email.format') ?? 'html';
|
||||
this.replyTo = config.getOptionalString('notifications.email.replyTo');
|
||||
this.cacheTtl =
|
||||
config.getOptionalNumber('notifications.email.cache.ttl') ?? 3_600_000;
|
||||
@@ -198,6 +197,55 @@ export class NotificationsEmailProcessor implements NotificationProcessor {
|
||||
return await this.getUserEmail(notification.user);
|
||||
}
|
||||
|
||||
private async sendPlainEmail(notification: Notification, emails: string[]) {
|
||||
const contentParts: string[] = [];
|
||||
if (notification.payload.description) {
|
||||
contentParts.push(`${notification.payload.description}`);
|
||||
}
|
||||
if (notification.payload.link) {
|
||||
contentParts.push(`${notification.payload.link}`);
|
||||
}
|
||||
|
||||
const mailOptions = {
|
||||
from: this.sender,
|
||||
subject: notification.payload.title,
|
||||
html: `<p>${contentParts.join('<br/>')}</p>`,
|
||||
text: contentParts.join('\n\n'),
|
||||
replyTo: this.replyTo,
|
||||
};
|
||||
|
||||
for (const email of emails) {
|
||||
try {
|
||||
await this.transporter.sendMail({ ...mailOptions, to: email });
|
||||
} catch (e) {
|
||||
this.logger.error(`Failed to send email to ${email}: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async sendTemplateEmail(
|
||||
notification: Notification,
|
||||
emails: string[],
|
||||
) {
|
||||
const mailOptions = {
|
||||
from: this.sender,
|
||||
subject:
|
||||
this.templateRenderer?.getSubject?.(notification) ??
|
||||
notification.payload.title,
|
||||
html: this.templateRenderer?.getHtml?.(notification),
|
||||
text: this.templateRenderer?.getText?.(notification),
|
||||
replyTo: this.replyTo,
|
||||
};
|
||||
|
||||
for (const email of emails) {
|
||||
try {
|
||||
await this.transporter.sendMail({ ...mailOptions, to: email });
|
||||
} catch (e) {
|
||||
this.logger.error(`Failed to send email to ${email}: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async postProcess(
|
||||
notification: Notification,
|
||||
options: NotificationSendOptions,
|
||||
@@ -219,32 +267,11 @@ export class NotificationsEmailProcessor implements NotificationProcessor {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: add template support for content either HTML or text
|
||||
const contentParts: string[] = [];
|
||||
if (notification.payload.description) {
|
||||
contentParts.push(`${notification.payload.description}`);
|
||||
}
|
||||
if (notification.payload.link) {
|
||||
contentParts.push(`${notification.payload.link}`);
|
||||
if (!this.templateRenderer) {
|
||||
await this.sendPlainEmail(notification, emails);
|
||||
return;
|
||||
}
|
||||
|
||||
const mailOptions = {
|
||||
from: this.sender,
|
||||
subject: notification.payload.title,
|
||||
html:
|
||||
this.format === 'html'
|
||||
? `<p>${contentParts.join('<br/>')}</p>`
|
||||
: undefined,
|
||||
text: this.format === 'text' ? contentParts.join('\n\n') : undefined,
|
||||
replyTo: this.replyTo,
|
||||
};
|
||||
|
||||
for (const email of emails) {
|
||||
try {
|
||||
await this.transporter.sendMail({ ...mailOptions, to: email });
|
||||
} catch (e) {
|
||||
this.logger.error(`Failed to send email to ${email}: ${e}`);
|
||||
}
|
||||
}
|
||||
await this.sendTemplateEmail(notification, emails);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user