Skip to content

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

refactor mail fowarding to detect forwarded mail based on recipient being the inbound mail

ThieryMicheld1f34c572816
diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.ts
index 6e9d40ad..5d7ccd1c 100644
--- a/supabase/functions/postmark/addNoteToContact.ts
+++ b/supabase/functions/postmark/addNoteToContact.ts
@@ -24,11 +24,13 @@ export const addNoteToContact = async ({
.eq("email", salesEmail)
.neq("disabled", true)
.maybeSingle();
- if (fetchSalesError)
+
+ if (fetchSalesError) {
return new Response(
`Could not fetch sales from database, email: ${salesEmail}`,
{ status: 500 },
);
+ }
if (!sales) {
// Return a 403 to let Postmark know that it's no use to retry this request
// https://postmarkapp.com/developer/webhooks/inbound-webhook#errors-and-retries
@@ -45,11 +47,12 @@ export const addNoteToContact = async ({
.select("*")
.contains("email_jsonb", JSON.stringify([{ email }]))
.maybeSingle();
- if (fetchContactError)
+ if (fetchContactError) {
return new Response(
`Could not fetch contact from database, email: ${email}`,
{ status: 500 },
);
+ }
// deno-lint-ignore no-explicit-any
let contact: any = undefined;
@@ -65,11 +68,12 @@ export const addNoteToContact = async ({
.select("*")
.eq("name", domain)
.maybeSingle();
- if (fetchCompanyError)
+ if (fetchCompanyError) {
return new Response(
`Could not fetch companies from database, name: ${domain}`,
{ status: 500 },
);
+ }
// deno-lint-ignore no-explicit-any
let company: any = undefined;
@@ -81,11 +85,12 @@ export const addNoteToContact = async ({
.from("companies")
.insert({ name: domain, sales_id: sales.id })
.select();
- if (createCompanyError)
+ if (createCompanyError) {
return new Response(
`Could not create company in database, name: ${domain}`,
{ status: 500 },
);
+ }
company = newCompanies[0];
}
@@ -103,11 +108,12 @@ export const addNoteToContact = async ({
tags: [],
})
.select();
- if (createContactError || !newContacts[0])
+ if (createContactError || !newContacts[0]) {
return new Response(
`Could not create contact in database, email: ${email}`,
{ status: 500 },
);
+ }
contact = newContacts[0];
}
@@ -120,11 +126,12 @@ export const addNoteToContact = async ({
sales_id: sales.id,
attachments,
});
- if (createNoteError)
+ if (createNoteError) {
return new Response(
`Could not add note to contact ${email}, sales ${salesEmail}`,
{ status: 500 },
);
+ }
await supabaseAdmin
.from("contacts")
diff --git a/supabase/functions/postmark/detectForwarded.spec.ts b/supabase/functions/postmark/detectForwarded.spec.ts
deleted file mode 100644
index cf2a0532..00000000
--- a/supabase/functions/postmark/detectForwarded.spec.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import {
- detectForwarded,
- parseForwardedBlock,
- parseFromLine,
-} from "./detectForwarded.ts";
-import { describe, expect, it } from "vitest";
-
-describe("detectForwarded", () => {
- it("detects Gmail forwarded block", () => {
- const subject = "Fwd: Project update";
- const textBody = `Hello team,
-
------ Forwarded message -----
-From: John Doe <[email protected]>
-Date: Mon, 1 Jan 2024 10:00:00 +0000
-Subject: Re: Project update
-
-This is the original message body.`;
- const result = detectForwarded(subject, textBody);
- expect(result.isForwarded).toBe(true);
- expect(result.originalFrom!).toEqual({
- name: "John Doe",
- email: "[email protected]",
- });
- expect(result.originalBody).toBe("This is the original message body.");
- });
-
- it("detects Apple Mail forwarded block", () => {
- const subject = "FW: Meeting notes";
- const textBody = `Begin forwarded message:
-From: Jane Smith <[email protected]>
-Date: Tue, 2 Feb 2024 09:00:00 +0000
-Subject: Meeting notes
-
-Here are the meeting notes.`;
- const result = detectForwarded(subject, textBody);
- expect(result.isForwarded).toBe(true);
- expect(result.originalFrom).toEqual({
- name: "Jane Smith",
- email: "[email protected]",
- });
- expect(result.originalBody).toBe("Here are the meeting notes.");
- });
-
- it("detects Outlook forwarded block", () => {
- const subject = "Fwd: Budget";
- const textBody = `-----Original Message-----
-From: Bob Brown <[email protected]>
-Sent: Wednesday, March 3, 2024 8:00 AM
-Subject: Budget
-
-Budget details attached.`;
- const result = detectForwarded(subject, textBody);
- expect(result.isForwarded).toBe(true);
- expect(result.originalFrom).toEqual({
- name: "Bob Brown",
- email: "[email protected]",
- });
- expect(result.originalBody).toBe("Budget details attached.");
- });
-
- it("detects Resent-From header", () => {
- const subject = "Fwd: Invoice";
- const textBody = "See attached invoice.";
- const headers = [
- { Name: "Resent-From", Value: "Alice <[email protected]>" },
- ];
- const result = detectForwarded(subject, textBody, headers);
- expect(result.isForwarded).toBe(true);
- expect(result.originalFrom).toEqual({
- name: "Alice",
- email: "[email protected]",
- });
- });
-
- it("handles malformed From line", () => {
- const subject = "Fwd: Weird format";
- const textBody = `----- Forwarded message -----
-From: not-an-email
-Date: Mon, 1 Jan 2024 10:00:00 +0000
-Subject: Re: Project update
-
-Body text.`;
- const result = detectForwarded(subject, textBody);
- expect(result.isForwarded).toBe(true);
- expect(result.originalFrom).toBeUndefined();
- expect(result.originalBody).toBe("Body text.");
- });
-
- describe("parseFromLine", () => {
- it("parses 'Name <email>' format", () => {
- const result = parseFromLine("John Doe <[email protected]>");
- expect(result).toEqual({ name: "John Doe", email: "[email protected]" });
- });
-
- it("parses 'email' format", () => {
- const result = parseFromLine("[email protected]");
- expect(result).toEqual({ name: "", email: "[email protected]" });
- });
-
- it("returns undefined for invalid format", () => {
- const result = parseFromLine("not-an-email");
- expect(result).toBeUndefined();
- });
- });
-
- describe("parseForwardedBlock", () => {
- it("parses forwarded block with From and body", () => {
- const blockText = `From: John Doe <[email protected]>
-Date: Mon, 1 Jan 2024 10:00:00 +0000
-Subject: Hello
-
-This is the original message body.`;
- const result = parseForwardedBlock(blockText);
- expect(result.originalFrom).toEqual({
- name: "John Doe",
- email: "[email protected]",
- });
- expect(result.originalBody).toBe("This is the original message body.");
- });
-
- it("handles missing From line", () => {
- const blockText = `Date: Mon, 1 Jan 2024 10:00:00 +0000
-Subject: Hello
-
-Body without From line.`;
- const result = parseForwardedBlock(blockText);
- expect(result.originalFrom).toBeUndefined();
- expect(result.originalBody).toBe("Body without From line.");
- });
-
- it("handles no blank line by leaving the body untounched", () => {
- const blockText = `From: John Doe <[email protected]>
-This is the body without a blank line separator.`;
- const result = parseForwardedBlock(blockText);
- expect(result.originalFrom).toEqual({
- name: "John Doe",
- email: "[email protected]",
- });
- expect(result.originalBody).toBe(
- "From: John Doe <[email protected]>\nThis is the body without a blank line separator.",
- );
- });
- });
-});
diff --git a/supabase/functions/postmark/detectForwarded.ts b/supabase/functions/postmark/detectForwarded.ts
deleted file mode 100644
index e0ea93d8..00000000
--- a/supabase/functions/postmark/detectForwarded.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-/**
- * Detects whether an inbound email is a forwarded message, and if so,
- * extracts the original sender and body.
- *
- * Detection strategy (in order of preference):
- * 1. RFC 5321 `Resent-From` header — most reliable, set by some clients.
- * 2. Known body separator patterns injected by Gmail, Outlook, Apple Mail, etc.
- *
- * Returns:
- * - isForwarded: true when a forwarding signal was detected
- * - originalFrom: parsed { name, email } of the original sender (may be undefined if parsing failed)
- * - originalBody: the body of the original message, minus the forwarding header block
- */
-
-export type ForwardedInfo = {
- isForwarded: boolean;
- originalFrom?: { name: string; email: string };
- originalBody?: string;
-};
-
-/** Patterns that mark the beginning of a forwarded block in the email body. */
-const FORWARD_SEPARATOR_PATTERNS = [
- // Gmail
- /^-{5,}\s*Forwarded message\s*-{5,}/im,
- // Apple Mail
- /^Begin forwarded message:/im,
- // Outlook / Exchange
- /^-{5,}\s*Original Message\s*-{5,}/im,
- // Outlook horizontal line separator
- /^_{10,}/m,
- // French clients (Transféré / Message transféré)
- /^-{5,}\s*Message transf[eé]r[eé]\s*-{5,}/im,
- /^-{5,}\s*Transf[eé]r[eé]\s*-{5,}/im,
- // German (Weitergeleitet)
- /^-{5,}\s*Weitergeleitete Nachricht\s*-{5,}/im,
-];
-
-/**
- * Parses a raw "From" header value such as:
- * "John Doe" <[email protected]>
- * John Doe <[email protected]>
- */
-export const parseFromLine = (
- raw: string,
-): { name: string; email: string } | undefined => {
- // Format: "Name" <email> or Name <email>
- const angleMatch = raw.match(/^"?([^"<]*?)"?\s*<([^>]+)>\s*$/);
- if (angleMatch) {
- return { name: angleMatch[1].trim(), email: angleMatch[2].trim() };
- }
- // Bare email address
- const emailMatch = raw.match(/^[\w.+%-]+@[\w.-]+\.[a-zA-Z]{2,}$/);
- if (emailMatch) {
- return { name: "", email: raw.trim() };
- }
- return undefined;
-};
-
-/**
- * Given the text that follows a forwarding separator, extracts the original
- * sender's From line and the body that comes after the header block.
- *
- * The header block is a sequence of lines that look like "Key: value"
- * (From, Date, Subject, To, Cc, …), potentially followed by a blank line.
- */
-export const parseForwardedBlock = (
- blockText: string,
-): {
- originalFrom?: { name: string; email: string };
- originalBody?: string;
-} => {
- const lines = blockText.split("\n");
- let originalFrom: { name: string; email: string } | undefined;
- let bodyStartIndex = 0;
-
- // Walk through the header-like lines at the top of the block
- let i = 0;
- while (i < lines.length) {
- const line = lines[i];
- // Blank line signals end of the forwarded header block
- if (line.trim() === "") {
- bodyStartIndex = i + 1;
- break;
- }
- // Try to capture the From: line
- const fromMatch = line.match(/^From:\s*(.+)$/i);
- if (fromMatch) {
- originalFrom = parseFromLine(fromMatch[1].trim());
- }
- i++;
- }
-
- const originalBody = lines.slice(bodyStartIndex).join("\n").trim();
- return { originalFrom, originalBody };
-};
-
-export const detectForwarded = (
- subject: string,
- textBody: string,
- headers: { Name: string; Value: string }[] = [],
-): ForwardedInfo => {
- // ── Strategy 1: Resent-From header ──────────────────────────────────────────
- const resentFrom = headers.find(
- (h) => h.Name.toLowerCase() === "resent-from",
- );
- if (resentFrom) {
- const originalFrom = parseFromLine(resentFrom.Value);
- return { isForwarded: true, originalFrom };
- }
-
- // ── Strategy 2: Body separator patterns ─────────────────────────────────────
- for (const pattern of FORWARD_SEPARATOR_PATTERNS) {
- const match = textBody.match(pattern);
- if (match && match.index !== undefined) {
- const blockText = textBody
- .slice(match.index + match[0].length)
- .trimStart();
- const { originalFrom, originalBody } = parseForwardedBlock(blockText);
- return { isForwarded: true, originalFrom, originalBody };
- }
- }
-
- return { isForwarded: false };
-};
diff --git a/supabase/functions/postmark/forwardedParser.test.ts b/supabase/functions/postmark/forwardedParser.test.ts
new file mode 100644
index 00000000..31f9e9ee
--- /dev/null
+++ b/supabase/functions/postmark/forwardedParser.test.ts
@@ -0,0 +1,244 @@
+import { describe, it, expect } from "vitest";
+import {
+ stripForwardingHeaderBlock,
+ stripSubjectForwardingPrefix,
+} from "./forwardedParser";
+
+describe("stripForwardingHeaderBlock", () => {
+ describe("returns original text when no forwarding separator is found", () => {
+ it("returns the original text for plain content", () => {
+ const text = "Hello, this is a regular email body.";
+ expect(stripForwardingHeaderBlock(text)).toBe(text);
+ });
+
+ it("trims whitespace when no separator is found", () => {
+ const text = " Hello world ";
+ expect(stripForwardingHeaderBlock(text)).toBe("Hello world");
+ });
+
+ it("returns original text when separator is not on the first line", () => {
+ const text =
+ "Some intro line\n---------- Forwarded message ----------\nActual content";
+ expect(stripForwardingHeaderBlock(text)).toBe(text.trim());
+ });
+ });
+
+ describe("Gmail forwarded separator", () => {
+ it("strips the Gmail forwarded header block", () => {
+ const text = [
+ "---------- Forwarded message ----------",
+ "From: Alice <[email protected]>",
+ "Date: Mon, 24 Feb 2026 10:00:00 +0000",
+ "Subject: Meeting notes",
+ "To: Bob <[email protected]>",
+ "",
+ "Hi Bob,",
+ "",
+ "Here are the meeting notes.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(
+ "Hi Bob,\n\nHere are the meeting notes.",
+ );
+ });
+ });
+
+ describe("Apple Mail forwarded separator", () => {
+ it("strips the Apple Mail forwarded header block", () => {
+ const text = [
+ "Begin forwarded message:",
+ "From: Alice <[email protected]>",
+ "Subject: Hello",
+ "Date: 24 Feb 2026",
+ "To: Bob <[email protected]>",
+ "",
+ "This is the original message.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(
+ "This is the original message.",
+ );
+ });
+ });
+
+ describe("Outlook / Exchange forwarded separator", () => {
+ it("strips the Outlook forwarded header block", () => {
+ const text = [
+ "-----Original Message-----",
+ "From: Alice <[email protected]>",
+ "Sent: Monday, February 24, 2026 10:00 AM",
+ "To: Bob <[email protected]>",
+ "Subject: Project update",
+ "",
+ "Please find the update below.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(
+ "Please find the update below.",
+ );
+ });
+ });
+
+ describe("French forwarded separators", () => {
+ it("strips the 'Message transféré' header block", () => {
+ const text = [
+ "---------- Message transféré ----------",
+ "De : Alice <[email protected]>",
+ "Date : 24 févr. 2026",
+ "Objet : Réunion",
+ "",
+ "Bonjour,",
+ "",
+ "Voici le message.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(
+ "Bonjour,\n\nVoici le message.",
+ );
+ });
+
+ it("strips the 'Transféré' header block", () => {
+ const text = [
+ "----- Transféré -----",
+ "De : Alice <[email protected]>",
+ "",
+ "Le message transféré.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe("Le message transféré.");
+ });
+
+ it("strips the ASCII-variant 'Message transfere' header block", () => {
+ const text = [
+ "---------- Message transfere ----------",
+ "De : Alice <[email protected]>",
+ "",
+ "Bonjour.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe("Bonjour.");
+ });
+ });
+
+ describe("German forwarded separator", () => {
+ it("strips the 'Weitergeleitete Nachricht' header block", () => {
+ const text = [
+ "---------- Weitergeleitete Nachricht ----------",
+ "Von: Alice <[email protected]>",
+ "Datum: 24. Feb. 2026",
+ "Betreff: Projekt",
+ "",
+ "Hallo,",
+ "",
+ "Hier ist die Nachricht.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(
+ "Hallo,\n\nHier ist die Nachricht.",
+ );
+ });
+ });
+
+ describe("edge cases", () => {
+ it("returns original text when stripping results in an empty body", () => {
+ const text = [
+ "---------- Forwarded message ----------",
+ "From: Alice <[email protected]>",
+ ].join("\n");
+
+ // No blank line → bodyStartIndex stays 0, slicing from 0 is the whole text.
+ // In this case, the while loop never finds a blank line and bodyStartIndex = 0.
+ // The strippedBody will be the original text trimmed.
+ expect(stripForwardingHeaderBlock(text)).toBe(text.trim());
+ });
+
+ it("returns original text when body after header block is empty", () => {
+ const text = [
+ "---------- Forwarded message ----------",
+ "From: Alice <[email protected]>",
+ "",
+ " ",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(text.trim());
+ });
+
+ it("preserves multi-paragraph body content", () => {
+ const text = [
+ "---------- Forwarded message ----------",
+ "From: Alice <[email protected]>",
+ "",
+ "First paragraph.",
+ "",
+ "Second paragraph.",
+ "",
+ "Third paragraph.",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe(
+ "First paragraph.\n\nSecond paragraph.\n\nThird paragraph.",
+ );
+ });
+
+ it("trims leading and trailing whitespace from the result", () => {
+ const text = [
+ "---------- Forwarded message ----------",
+ "From: Alice",
+ "",
+ " ",
+ " Body content ",
+ " ",
+ ].join("\n");
+
+ expect(stripForwardingHeaderBlock(text)).toBe("Body content");
+ });
+ });
+});
+
+describe("stripSubjectForwardingPrefix", () => {
+ it("strips 'Fwd:' prefix", () => {
+ expect(stripSubjectForwardingPrefix("Fwd: Hello")).toBe("Hello");
+ });
+
+ it("strips 'FW:' prefix", () => {
+ expect(stripSubjectForwardingPrefix("FW: Hello")).toBe("Hello");
+ });
+
+ it("strips 'FWD:' prefix", () => {
+ expect(stripSubjectForwardingPrefix("FWD: Hello")).toBe("Hello");
+ });
+
+ it("strips 'Tr:' prefix (French)", () => {
+ expect(stripSubjectForwardingPrefix("Tr: Bonjour")).toBe("Bonjour");
+ });
+
+ it("strips 'SV:' prefix (Scandinavian)", () => {
+ expect(stripSubjectForwardingPrefix("SV: Hei")).toBe("Hei");
+ });
+
+ it("strips 'VS:' prefix", () => {
+ expect(stripSubjectForwardingPrefix("VS: Hallo")).toBe("Hallo");
+ });
+
+ it("strips 'WG:' prefix (German)", () => {
+ expect(stripSubjectForwardingPrefix("WG: Hallo")).toBe("Hallo");
+ });
+
+ it("is case-insensitive", () => {
+ expect(stripSubjectForwardingPrefix("fwd: lowercase")).toBe("lowercase");
+ expect(stripSubjectForwardingPrefix("FWD - Mixed")).toBe("Mixed");
+ });
+
+ it("returns the subject unchanged when no prefix is present", () => {
+ expect(stripSubjectForwardingPrefix("Meeting notes")).toBe("Meeting notes");
+ });
+
+ it("handles dash separator instead of colon", () => {
+ expect(stripSubjectForwardingPrefix("Fwd - My subject")).toBe("My subject");
+ });
+
+ it("should return original subject if stripping results in empty string", () => {
+ const subject = "Fwd: ";
+ expect(stripSubjectForwardingPrefix(subject)).toBe(subject);
+ });
+});
diff --git a/supabase/functions/postmark/forwardedParser.ts b/supabase/functions/postmark/forwardedParser.ts
new file mode 100644
index 00000000..54eb9734
--- /dev/null
+++ b/supabase/functions/postmark/forwardedParser.ts
@@ -0,0 +1,68 @@
+/** Patterns that mark the beginning of a forwarded block in the email body. */
+const FORWARD_SEPARATOR_PATTERNS = [
+ // Gmail
+ /^-{5,}\s*Forwarded message\s*-{5,}/im,
+ // Apple Mail
+ /^Begin forwarded message:/im,
+ // Outlook / Exchange
+ /^-{5,}\s*Original Message\s*-{5,}/im,
+ // French clients (Transféré / Message transféré)
+ /^-{5,}\s*Message transf[eé]r[eé]\s*-{5,}/im,
+ /^-{5,}\s*Transf[eé]r[eé]\s*-{5,}/im,
+ // German (Weitergeleitet)
+ /^-{5,}\s*Weitergeleitete Nachricht\s*-{5,}/im,
+];
+
+export const stripForwardingHeaderBlock = (text: string): string => {
+ const lines = text.split("\n");
+ let bodyStartIndex = 0;
+
+ // First check that the first line matches a known forwarding separator pattern
+ const hasForwardedSeparator = FORWARD_SEPARATOR_PATTERNS.some((pattern) => {
+ const match = lines[0].match(pattern);
+ return !!match;
+ });
+ if (!hasForwardedSeparator) {
+ // No known forwarding pattern detected, return the original text
+ return text.trim();
+ }
+
+ // Walk through the header-like lines at the top of the block
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i];
+ // Blank line signals end of the forwarded header block
+ if (line.trim() === "") {
+ bodyStartIndex = i + 1;
+ break;
+ }
+ i++;
+ }
+
+ const strippedBody = lines.slice(bodyStartIndex).join("\n").trim();
+
+ if (strippedBody === "") {
+ // If stripping the header block results in an empty body, return the original text
+ console.warn(
+ "Stripping forwarded header block resulted in empty body, returning original text",
+ );
+ return text.trim();
+ }
+
+ return strippedBody;
+};
+
+export const stripSubjectForwardingPrefix = (subject: string): string => {
+ const result = subject
+ .replace(/^(Fwd|FW|FWD|Tr|SV|VS|WG|WG:)\s*[:-]\s*/i, "")
+ .trim();
+
+ if (result.length === 0) {
+ console.warn(
+ `Stripping forwarding prefix from subject "${subject}" resulted in empty string, returning original subject`,
+ );
+ return subject;
+ }
+
+ return result;
+};
diff --git a/supabase/functions/postmark/index.ts b/supabase/functions/postmark/index.ts
index 9d97621d..5a75a6fa 100644
--- a/supabase/functions/postmark/index.ts
+++ b/supabase/functions/postmark/index.ts
@@ -5,11 +5,15 @@
// Setup type definitions for built-in Supabase Runtime APIs
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { addNoteToContact } from "./addNoteToContact.ts";
-import { detectForwarded } from "./detectForwarded.ts";
+import {
+ stripForwardingHeaderBlock,
+ stripSubjectForwardingPrefix,
+} from "./forwardedParser.ts";
import { extractMailContactData } from "./extractMailContactData.ts";
import { getExpectedAuthorization } from "./getExpectedAuthorization.ts";
import { getNoteContent } from "./getNoteContent.ts";
import { extractAndUploadAttachments } from "./extractAndUploadAttachments.ts";
+import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";
const webhookUser = Deno.env.get("POSTMARK_WEBHOOK_USER");
const webhookPassword = Deno.env.get("POSTMARK_WEBHOOK_PASSWORD");
@@ -25,6 +29,10 @@ if (!rawAuthorizedIPs) {
}
Deno.serve(async (req) => {
+ const allSales = await supabaseAdmin.from("sales").select("email");
+ const salesEmails =
+ allSales.data?.map((s: { email: string }) => s.email) ?? [];
+
let response: Response | undefined;
response = checkRequestTypeAndHeaders(req);
@@ -34,8 +42,8 @@ Deno.serve(async (req) => {
response = checkBody(json);
if (response) return response;
- const { FromFull, Subject, Attachments, Headers } = json;
- let { ToFull, TextBody } = json;
+ const { FromFull, Attachments } = json;
+ let { ToFull, TextBody, Subject } = json;
const { Email: salesEmail } = FromFull;
if (!salesEmail) {
@@ -47,34 +55,33 @@ Deno.serve(async (req) => {
);
}
- // Detect forwarded emails and reroute the note to the original sender
- const forwarded = detectForwarded(Subject, TextBody, Headers ?? []);
- if (forwarded.isForwarded) {
- if (!forwarded.originalFrom) {
- // Could not parse the original sender — log and fall through to default
- // behavior so the email is not silently lost.
- console.warn(
- "Detected a forwarded email but could not extract the original sender. " +
- "Falling back to default contact resolution.",
- {
- subject: Subject,
- textBody: TextBody,
- headers: Headers,
- },
- );
- } else {
- // Swap the recipient with the original sender so the note is attached to
- // the right contact, and trim the note to only the original message body.
+ // This env var is only available inside the served function
+ const INBOUND_EMAIL = process.env.VITE_INBOUND_EMAIL;
+
+ // If the email is sent to the inbound email address, and the sender is a known sales email,
+ // then we can try to extract the real recipient email from the body of the email
+ if (
+ ToFull.length === 1 &&
+ ToFull[0].Email === INBOUND_EMAIL &&
+ salesEmails.includes(FromFull.Email)
+ ) {
+ const emailRegex = /[\w.+%-]+@[\w.-]+\.[a-zA-Z]{2,}/g;
+ const emailsInBody = TextBody.match(emailRegex) || [];
+
+ const candidateEmails = emailsInBody.filter(
+ (email: string) =>
+ email !== INBOUND_EMAIL && !salesEmails?.includes(email),
+ );
+ if (candidateEmails.length > 0) {
ToFull = [
{
- Email: forwarded.originalFrom.email,
- Name: forwarded.originalFrom.name,
+ Email: candidateEmails[0],
+ Name: "",
},
];
- if (forwarded.originalBody) {
- TextBody = forwarded.originalBody;
- }
}
+ TextBody = stripForwardingHeaderBlock(TextBody);
+ Subject = stripSubjectForwardingPrefix(Subject);
}
const noteContent = getNoteContent(Subject, TextBody);
@@ -115,7 +122,9 @@ const checkRequestTypeAndHeaders = (req: Request) => {
return new Response("Unauthorized", { status: 401 });
}
const ips = forwardedFor.split(",").map((ip) => ip.trim());
- const authorizedIPs = rawAuthorizedIPs.split(",").map((ip) => ip.trim());
+ const authorizedIPs = rawAuthorizedIPs
+ .split(",")
+ .map((ip: string) => ip.trim());
if (!ips.some((ip) => authorizedIPs.includes(ip))) {
return new Response("Unauthorized", { status: 401 });
}