Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add email download #23

Merged
merged 1 commit into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/emlFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createTransport, Transporter } from "nodemailer";
import { convertToMailOptions, Email } from "./store";

export interface CreateEmlContentResult {
messageId: string,
error?: string,
fileName: string,
body: string
}

export const createEmlContent = async (email: Email): Promise<CreateEmlContentResult> => {

const transporter: Transporter = createTransport({
streamTransport: true,
buffer: true,
});

return new Promise((resolve, reject) => {
transporter.sendMail(convertToMailOptions(email), (error, info) => {
if (!error) {
resolve({ messageId: email.messageId, fileName: email.subject, body: info.message });
} else {
reject({ messageId: email.messageId, error: `failed to create eml file content, ${error.message}` });
}
});
})
};
24 changes: 23 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import v2DeleteEmailTemplate from './v2/deleteEmailTemplate';
import v2GetAccount from './v2/getAccount';
import v2SendEmail from './v2/sendEmail';
import v2SendBulkEmail from './v2/sendBulkEmail';
import { getStoreReadonly, clearStore } from './store';
import { getStoreReadonly, clearStore, Email } from './store';
import { createEmlContent } from './emlFile';

export interface Config {
host: string,
Expand Down Expand Up @@ -62,6 +63,27 @@ const server = (partialConfig: Partial<Config> = {}): Promise<Server> => {
app.get('/health-check', (req, res) => {
res.status(200).send();
});

app.get('/get-emlContent', (req, res) => {
const store = getStoreReadonly();

if (typeof req.query.messageId !== 'string' || req.query.messageId === '') {
res.status(400).send({ message: 'Bad since query param, expected single value' });
}

const messageId = req.query.messageId as string;
const email = store.emails.find(e => e.messageId === messageId);

if (email === undefined) {
res.status(400).send({ message: 'Email not found within the store' })
}

createEmlContent(email as Email).then((result) => {
res.status(200).send(result);
}).catch((result) => {
res.status(400).send({ message: result.error });
});
});

app.use((req, res, next) => {
const authHeader = req.header('authorization');
Expand Down
14 changes: 14 additions & 0 deletions src/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { sendEmailToSmtp } from './smtp';
import { MailOptions } from 'nodemailer/lib/sendmail-transport';

export interface Store {
emails: Email[],
Expand Down Expand Up @@ -56,3 +57,16 @@ export const clearStore = () => {
// But this is probably safe enough for now, given the method name
// and the relatively small project size.
export const getStoreReadonly = (): Readonly<Store> => store;

export const convertToMailOptions = (email: Email): MailOptions => ({
from: email.from,
replyTo: email.replyTo,
to: email.destination.to,
cc: email.destination.cc,
bcc: email.destination.bcc,
subject: email.subject,
html: email.body.html,
text: email.body.text,
attachments: email.attachments,
date: new Date(email.at * 1000)
});
18 changes: 18 additions & 0 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ <h2>Error: You need JavaScript enabled for this page to work.</h2>
${e.body.text ? `<button onclick="toggle('${e.messageId}-text')">Toggle text view</button>` : ''}
${e.body.html ? `<button onclick="toggle('${e.messageId}-html')">Toggle HTML view</button>` : ''}
${e.body.html ? `<button onclick="toggle('${e.messageId}-source')">Toggle HTML source view</button>` : ''}
<button onclick="downloadEmail('${e.messageId}')">Email Download</button>

${e.body.text ? `<div class="email-text" id="${e.messageId}-text" style="display: none">${escape(e.body.text)}</div>` : ''}
${e.body.html ? `<div class="email-html" id="${e.messageId}-html" style="display: none"><iframe id="${e.messageId}-html-iframe" src="javascript:void(0);"></iframe></div>` : ''}
Expand Down Expand Up @@ -307,6 +308,23 @@ <h2>Error: You need JavaScript enabled for this page to work.</h2>
location.reload();
}

const downloadEmail = async (messageId) => {
let res;
try {
res = await fetch(`/get-emlContent?messageId=${messageId}`);
} catch (err) {
showError('Couldn\'t fetch required content for download.', 'The email may have been removed from store. See the browser console for more details.')
console.error(err)
return;
}
const emlContent = await res.json();

const a = document.createElement('a');
a.href = makeBlob('message/rfc822', btoa(String.fromCharCode.apply(null, emlContent.body.data)));
a.download = `${emlContent.fileName}.eml`;
a.click();
}

let theme = getTheme()
document.documentElement.setAttribute('data-theme', theme);

Expand Down
43 changes: 43 additions & 0 deletions test/getEmlContent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { SES, SendEmailCommand } from '@aws-sdk/client-ses';
import axios from 'axios';
import { Store } from '../src/store';
import { CreateEmlContentResult } from '../src/emlFile';
import { baseURL } from './globals';

test('can get eml content', async () => {
const ses = new SES({
endpoint: baseURL,
region: 'aws-ses-v2-local',
credentials: { accessKeyId: 'ANY_STRING', secretAccessKey: 'ANY_STRING' },
});
await ses.send(new SendEmailCommand({
Source: 'sender@example.com',
Destination: { ToAddresses: ['receiver@example.com'] },
Message: {
Subject: { Data: 'This is the subject' },
Body: { Text: { Data: 'This is the email contents' } },
},
}));
const storeWithEmails: Store = (await axios({
method: 'get',
baseURL,
url: '/store',
})).data;
expect(storeWithEmails.emails).toHaveLength(1);
const messageId = storeWithEmails.emails[0].messageId;

const c: CreateEmlContentResult = (await axios({
method: 'get',
url: `/get-emlContent?messageId=${messageId}`,
baseURL,
})).data;

expect(c).toMatchObject({
messageId: messageId,
fileName: 'This is the subject',
body: {
type: "Buffer",
data: expect.any(Array<String>),
}
});
});