import { createMimeMessage } from "mimetext"; import { EmailMessage } from "cloudflare:email"; import PostalMime from "postal-mime"; async function streamToArrayBuffer(stream, streamSize) { let result = new Uint8Array(streamSize); let bytesRead = 0; const reader = stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) { break; } result.set(value, bytesRead); bytesRead += value.length; } return result; } export async function run({ message, env }) { const extraHeaders = new Headers(); const raw = await streamToArrayBuffer(message.raw, message.rawSize); const parsedMessage = await PostalMime.parse(raw); console.log("parsedMessage headers", parsedMessage.headers); console.log("parsedMessage to", parsedMessage.to); console.log("parsedMessage cc", parsedMessage.cc); console.log("parsedMessage subject", parsedMessage.subject); console.log("parsedMessage messageId", parsedMessage.messageId); console.log("parsedMessage from", parsedMessage.from); const variables = {}; async function scoreEmail() { const response = await env.AI.run("@cf/huggingface/distilbert-sst-2-int8", { text: raw, }); } try { if ( parsedMessage.headers["Fastmail-MaskedEmail"].value.includes( " state=disabled", ) ) { console.log("stop"); return; } } catch (err) { console.error("rule 4 failed and has been skipped", err); } try { if (parsedMessage.headers["X-Spam-Known-Sender"].value.match(/yes.*/)) { try { if (parsedMessage.headers["X-Backscatter"].value.includes("yes")) { try { if (parsedMessage.headers["X-LinkName"].value.match(/.*/)) { variables["local0"] = "Y"; delete variables["local1"]; } } catch (err) { console.error("rule 12 failed and has been skipped", err); } } } catch (err) { console.error("rule 12 failed and has been skipped", err); } } } catch (err) { console.error("rule 12 failed and has been skipped", err); } try { if ("" === "Y") { console.log("stop"); return; } } catch (err) { console.error("rule 15 failed and has been skipped", err); } try { if (raw.includes("MAKE MONEY FAST")) { console.log("discard"); // discard the email return; } } catch (err) { console.error("rule 18 failed and has been skipped", err); } try { if (raw.includes("to be saved")) { await env.BINDING_NAME.put("foobar", raw); } } catch (err) { console.error("rule 21 failed and has been skipped", err); } try { if ((await scoreEmail()) == 37) { console.log("discard"); // discard the email return; } } catch (err) { console.error("rule 24 failed and has been skipped", err); } }