Skip to content

Instantly share code, notes, and snippets.

@lottamus
Created July 17, 2024 20:01
Show Gist options
  • Save lottamus/f1533b352ec53581adfb6ad62a7c3124 to your computer and use it in GitHub Desktop.
Save lottamus/f1533b352ec53581adfb6ad62a7c3124 to your computer and use it in GitHub Desktop.
parses the email and forwards it to the appropriate recipient
import type {
ExportedHandler,
} from "@cloudflare/workers-types";
import PostalMime, { type Email } from "postal-mime";
/**
* This is the main entry point for the inbound email parsing service.
* It is triggered when an email is received at the inbound email address.
* It parses the email and forwards it to the appropriate recipient.
*/
const inboundParse: ExportedHandler = {
async email(message) {
const rawEmail = await streamToArrayBuffer(message.raw, message.rawSize);
const parser = new PostalMime();
const parsedEmail = await parser.parse(rawEmail);
const headers = Object.fromEntries(message.headers.entries());
const subject = message.headers.get("subject") || parsedEmail.subject;
// Forward the email to another email address
// await message.forward("email-address");
// OR send it to another API / store in a database
// fetch(...)
return;
},
};
async function streamToArrayBuffer(
stream: ReadableStream<ArrayLike<number>>,
streamSize: number,
) {
const result = new Uint8Array(streamSize);
let bytesRead = 0;
const reader = stream.getReader();
let isReading = true;
while (isReading) {
const { done, value } = await reader.read();
if (done) {
isReading = false;
break;
}
result.set(value, bytesRead);
bytesRead += value.length;
}
return result;
}
export default inboundParse;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment