Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
aca5ac1
Implement MS Graph Mail service
May 8, 2026
8e3f0c9
feat: complete ms graph api mail service
May 11, 2026
cac9762
fix: package files
May 11, 2026
6c6a63f
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 11, 2026
177cb99
fix: lazy creation of client
May 11, 2026
fc33512
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
May 11, 2026
0382853
feat: simplify ms graph mail service
May 11, 2026
4e27cf5
feat: simplify ms graph api mail service
May 11, 2026
326b54d
Merge branch 'develop' into feat_ms_graph_api_mail_service
May 12, 2026
5474a49
fix: add further logs
May 12, 2026
d927198
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 12, 2026
21fdb8d
Merge branch 'develop' of https://github.com/UserOfficeProject/user-o…
May 12, 2026
64464eb
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
May 12, 2026
0b7b056
feat: delete ms graph api test
May 12, 2026
700a505
fix: remove password log output
May 12, 2026
d609c8a
fix: make createAttachments abstract and fix ms graph implementation
May 12, 2026
ef96cb2
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 12, 2026
035f0b6
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 13, 2026
b225a12
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 14, 2026
722da5d
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 18, 2026
9258e20
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 19, 2026
6a85d85
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri May 20, 2026
e328c69
Merge from develop
May 26, 2026
3d27b24
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
May 26, 2026
9be23b7
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri Jun 2, 2026
f14e5ac
fix: review findings
Jun 2, 2026
ca40134
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri Jun 8, 2026
670a5ff
Merge branch 'develop' into feat_ms_graph_api_mail_service
Jun 8, 2026
e6ce663
Merge branch 'develop' into feat_ms_graph_api_mail_service
Jun 8, 2026
a2ae146
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
Jun 8, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions apps/backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@apollo/server": "^5.5.0",
"@apollo/subgraph": "^2.13.2",
"@as-integrations/express4": "^1.1.2",
"@azure/msal-node": "^5.2.0",
"@graphql-tools/utils": "^10.1.0",
"@isaacs/ttlcache": "^1.4.1",
"@opentelemetry/exporter-logs-otlp-http": "^0.216.0",
Expand Down
4 changes: 2 additions & 2 deletions apps/backend/src/config/dependencyConfigELI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import PostgresVisitRegistrationClaimDataSource from '../datasources/postgres/Vi
import PostgresWorkflowDataSource from '../datasources/postgres/WorkflowDataSource';
import { eliEmailHandler } from '../eventHandlers/email/eliEmailHandler';
import createLoggingHandler from '../eventHandlers/logging';
import { SMTPMailService } from '../eventHandlers/MailService/SMTP/SMTPMailService';
import { MSGraphMailService } from '../eventHandlers/MailService/MSGraph/MSGraphMailService';
import {
createListenToRabbitMQHandler,
createPostToRabbitMQHandler,
Expand Down Expand Up @@ -127,7 +127,7 @@ mapClass(Tokens.DataAccessUsersAuthorization, DataAccessUsersAuthorization);

mapClass(Tokens.AssetRegistrar, EAMAssetRegistrar);

mapClass(Tokens.MailService, SMTPMailService);
mapClass(Tokens.MailService, MSGraphMailService);

mapValue(Tokens.FapDataColumns, FapDataColumns);
mapValue(Tokens.FapDataRow, getDataRow);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import { existsSync, readFileSync } from 'node:fs';

import * as msal from '@azure/msal-node';
import { logger } from '@user-office-software/duo-logger';
import { NodeMailerTransportOptions } from 'email-templates';
import * as nodemailer from 'nodemailer';
import { SentMessageInfo, Transport } from 'nodemailer';
import MailMessage from 'nodemailer/lib/mailer/mail-message';

import { TemplateMailService } from '../TemplateMailService';

class MSGraphTransport implements Transport<SentMessageInfo> {
name: string;
version: string;

private apiUrl: string;
private authToken: msal.AuthenticationResult | null = null;
private msalClient: msal.ConfidentialClientApplication;
private tokenPromise: Promise<any> | null = null;

constructor() {
this.name = 'MSGraphTransport';
this.version = '1.0.0';
this.apiUrl = process.env.MS_GRAPH_API_URL || '';

this.msalClient = new msal.ConfidentialClientApplication({
auth: {
clientId: process.env.MS_GRAPH_API_CLIENT_ID!,
clientSecret: process.env.MS_GRAPH_API_CLIENT_SECRET!,
authority: `${process.env.MS_GRAPH_API_AUTHORITY}/${process.env.MS_GRAPH_API_TENANT_ID}`,
},
});
}

protected isTokenExpired(): boolean {
if (!this.authToken?.expiresOn) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug (maybe): I think this should return 'true'? If the field is missing then intuitively the token should be considered as expired... or?

throw new Error('Invalid token: Missing expiresOn property');
}

return Date.now() >= this.authToken.expiresOn.getTime();
}

private async getAuthToken(): Promise<msal.AuthenticationResult> {
// if we already have a valid token, return it
if (this.authToken && !this.isTokenExpired()) {
return this.authToken;
}

// cache the promise to prevent multiple simultaneous token requests
if (!this.tokenPromise) {
this.tokenPromise = (async () => {
try {
this.authToken = await this.msalClient.acquireTokenByClientCredential(
{
scopes: [`${this.apiUrl}/.default`],
}
);

logger.logInfo('Acquired new access token for Microsoft Graph API', {
expiresOn: this.authToken?.expiresOn,
});
} finally {
this.tokenPromise = null;
}
})();
}

return this.tokenPromise;
}

public async send(
message: MailMessage<SentMessageInfo>,
callback: (err: Error | null, info: unknown) => void
) {
try {
const token = await this.getAuthToken();

if (!token?.accessToken) {
throw new Error(
'Failed to acquire access token for Microsoft Graph API'
);
}

const {
subject,
to,
from,
html,
bcc,
attachments = [],
} = message.data || {};

const payload = {
message: {
subject: subject || '',
body: {
contentType: 'HTML',
content: html || '',
},
toRecipients: [
{
emailAddress: {
address: to,
},
},
],
bccRecipients: bcc
? [
{
emailAddress: {
address: bcc,
},
},
]
: undefined,
attachments: attachments,
},
saveToSentItems: true,
};

const response = await fetch(
`${this.apiUrl}/v1.0/users/${from}/sendMail`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${token.accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
}
);

if (!response.ok) {
logger.logError('Unable to send email to user', {
error: response.statusText + ' : ' + response.status,
});

throw new Error(
`Failed to send email. Status: ${response.status} - ${response.statusText}`
);
}

const responseData = await response.text();
callback(null, {
envelope: {
from: from,
to: [to],
},
messageId: '',
accepted: [],
rejected: [],
pending: [],
response: responseData,
});
} catch (error: any) {
logger.logError('Unable to send email to user', {
error: error,
});

callback(error, null);
}
}
}

export class MSGraphMailService extends TemplateMailService {
constructor() {
super();
}

protected createTransport(): NodeMailerTransportOptions {
return nodemailer.createTransport(new MSGraphTransport());
}

protected createAttachments() {
const attachments = [];

if (process.env.EMAIL_FOOTER_IMAGE_PATH !== undefined) {
if (existsSync(process.env.EMAIL_FOOTER_IMAGE_PATH)) {
attachments.push({
'@odata.type': '#microsoft.graph.fileAttachment',
name: 'logo.png',
contentType: 'image/png',
contentBytes: readFileSync(
process.env.EMAIL_FOOTER_IMAGE_PATH
).toString('base64'),
});
} else {
logger.logWarn('Email footer image path does not exist', {
path: process.env.EMAIL_FOOTER_IMAGE_PATH,
});
}
}

return attachments;
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import EmailTemplates from 'email-templates';
import { container } from 'tsyringe';

import { SMTPMailService } from './SMTPMailService';
import { Tokens } from '../../../config/Tokens';
import { AdminDataSource } from '../../../datasources/AdminDataSource';
import { SettingsId } from '../../../models/Settings';
import SendMailOptions from '../MailService';
import { SMTPMailService } from './SMTPMailService';

jest.mock('email-templates');
const mockAdminDataSource = container.resolve(
Expand Down
Loading
Loading