Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

feat(inbound-email): support attachments

Jean-Baptiste Kaiser22e27d5d04e2
diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.ts
index b9cf77c1..6e9d40ad 100644
--- a/supabase/functions/postmark/addNoteToContact.ts
+++ b/supabase/functions/postmark/addNoteToContact.ts
@@ -1,4 +1,5 @@
import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";
+import type { Attachment } from "./extractAndUploadAttachments.ts";
export const addNoteToContact = async ({
salesEmail,
@@ -7,6 +8,7 @@ export const addNoteToContact = async ({
firstName,
lastName,
noteContent,
+ attachments,
}: {
salesEmail: string;
email: string;
@@ -14,6 +16,7 @@ export const addNoteToContact = async ({
firstName: string;
lastName: string;
noteContent: string;
+ attachments: Attachment[];
}) => {
const { data: sales, error: fetchSalesError } = await supabaseAdmin
.from("sales")
@@ -115,6 +118,7 @@ export const addNoteToContact = async ({
contact_id: contact.id,
text: noteContent,
sales_id: sales.id,
+ attachments,
});
if (createNoteError)
return new Response(
diff --git a/supabase/functions/postmark/deno.json b/supabase/functions/postmark/deno.json
new file mode 100644
index 00000000..87fce9c6
--- /dev/null
+++ b/supabase/functions/postmark/deno.json
@@ -0,0 +1,5 @@
+{
+ "imports": {
+ "base64-arraybuffer": "npm:base64-arraybuffer"
+ }
+}
diff --git a/supabase/functions/postmark/extractAndUploadAttachments.ts b/supabase/functions/postmark/extractAndUploadAttachments.ts
new file mode 100644
index 00000000..64e8873e
--- /dev/null
+++ b/supabase/functions/postmark/extractAndUploadAttachments.ts
@@ -0,0 +1,97 @@
+import { decode } from "npm:base64-arraybuffer";
+import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";
+
+export type Attachment = {
+ title: string;
+ type: string;
+ path: string;
+ src: string;
+};
+
+/**
+ * Extracts the attachments from the email and upload them to Supabase Storage.
+ *
+ * Example:
+ * "Attachments": [
+ * {
+ * "Name": "test.txt",
+ * "Content": "VGhpcyBpcyBhdHRhY2htZW50IGNvbnRlbnRzLCBiYXNlLTY0IGVuY29kZWQu",
+ * "ContentType": "text/plain",
+ * "ContentLength": 45
+ * }
+ * ]
+ *
+ * Return Value:
+ * [{
+ * title: "test.txt",
+ * type: "text/plain",
+ * "path": "0.8262106278726917.txt",
+ * "src": "http://127.0.0.1:54321/storage/v1/object/public/attachments/0.8262106278726917.txt",
+ * }]
+ *
+ */
+export const extractAndUploadAttachments = async (
+ Attachments: {
+ Name: string;
+ Content: string;
+ ContentType: string;
+ ContentLength: number;
+ }[],
+): Promise<Attachment[]> => {
+ return (
+ await Promise.all(
+ (Attachments || []).map(async (attachment) => {
+ const { Name, Content, ContentType } = attachment;
+ if (!Name || !Content || !ContentType) {
+ console.warn("Attachment is missing required fields, skipping", {
+ attachment,
+ });
+ return null;
+ }
+
+ const decodedContent = decode(Content);
+ if (!decodedContent) {
+ console.error("Failed to decode attachment content, skipping", {
+ attachment,
+ });
+ return null;
+ }
+
+ const fileParts = Name.split(".");
+ const fileExt = fileParts.length > 1 ? `.${Name.split(".").pop()}` : "";
+ const fileName = `${Math.random()}${fileExt}`;
+ const { error: uploadError } = await supabaseAdmin.storage
+ .from("attachments")
+ .upload(fileName, decodedContent);
+
+ if (uploadError) {
+ console.error("uploadError", uploadError);
+ throw new Error("Failed to upload attachment");
+ }
+
+ const { data } = supabaseAdmin.storage
+ .from("attachments")
+ .getPublicUrl(fileName);
+
+ return {
+ title: Name,
+ type: ContentType,
+ path: fileName,
+ src: fixPublicUrl(data.publicUrl),
+ };
+ }),
+ )
+ ).filter(Boolean) as Attachment[];
+};
+
+/*
+ * Workaround fix for public URL not working on local environment
+ * See https://github.com/orgs/supabase/discussions/37271
+ *
+ * Replaces http://kong:8000/storage/v1/object/public/attachments/0.08968261048718773.txt with http://127.0.0.1:54321/storage/v1/object/public/attachments/0.08968261048718773.txt, using the SB_JWT_ISSUER env var (value http://127.0.0.1:54321/auth/v1) to get the external/public URL of the Supabase instance.
+ */
+const fixPublicUrl = (url: string) => {
+ const jwtIssuer = Deno.env.get("SB_JWT_ISSUER") ?? "";
+ const localUrl = jwtIssuer.replace("/auth/v1", "");
+ return url.replace("http://kong:8000", localUrl);
+};
diff --git a/supabase/functions/postmark/index.ts b/supabase/functions/postmark/index.ts
index 7b94d10e..cf7f97a9 100644
--- a/supabase/functions/postmark/index.ts
+++ b/supabase/functions/postmark/index.ts
@@ -8,6 +8,7 @@ import { addNoteToContact } from "./addNoteToContact.ts";
import { extractMailContactData } from "./extractMailContactData.ts";
import { getExpectedAuthorization } from "./getExpectedAuthorization.ts";
import { getNoteContent } from "./getNoteContent.ts";
+import { extractAndUploadAttachments } from "./extractAndUploadAttachments.ts";
const webhookUser = Deno.env.get("POSTMARK_WEBHOOK_USER");
const webhookPassword = Deno.env.get("POSTMARK_WEBHOOK_PASSWORD");
@@ -32,7 +33,7 @@ Deno.serve(async (req) => {
response = checkBody(json);
if (response) return response;
- const { ToFull, FromFull, Subject, TextBody } = json;
+ const { ToFull, FromFull, Subject, TextBody, Attachments } = json;
const noteContent = getNoteContent(Subject, TextBody);
@@ -48,6 +49,8 @@ Deno.serve(async (req) => {
const contacts = extractMailContactData(ToFull);
+ const attachments = await extractAndUploadAttachments(Attachments);
+
for (const { firstName, lastName, email, domain } of contacts) {
if (!email) {
// Return a 403 to let Postmark know that it's no use to retry this request
@@ -64,6 +67,7 @@ Deno.serve(async (req) => {
firstName,
lastName,
noteContent,
+ attachments,
});
}