Add email worker and use it to send email from pages function
Some checks failed
release / Publish to Cloudflare Pages (push) Failing after 1m17s

This commit is contained in:
2025-02-03 17:00:59 +10:30
parent 73a4ee7df4
commit d487f7ecb7
11 changed files with 2426 additions and 38 deletions

View File

@@ -1,9 +1,16 @@
import staticFormsPlugin from "@cloudflare/pages-plugin-static-forms";
import { EmailMessage } from "cloudflare:email";
interface SendEmailWorker {
sendEmail(rawMessage: string): Promise<Response>;
}
interface Env {
SERVICE: SendEmailWorker;
}
const formatEmptyString = (s: string) => s ?? "Not Specified";
export const onRequest: PagesFunction = (context) => {
export const onRequest: PagesFunction<Env> = (context) => {
// Wrap static forms plugin so we can extract the env to use email routing
return staticFormsPlugin({
respondWith: async ({ formData }) => {
@@ -15,38 +22,25 @@ export const onRequest: PagesFunction = (context) => {
// Must have some kind of identifiable information for me to actually care about them.
if ((fullName || email) && message) {
const rawEmailMessage = `----
From: Michael Pivato Contact Form <contact@michaelpivato.dev>
To: Michael Pivato <contact@michaelpivato.dev
Subject: Message from ${fullName ?? email}
You've received a new message from ${fullName ?? email}.
Full Name: ${formatEmptyString(fullName)}
Organisation: ${formatEmptyString(organisation)}
Email: ${formatEmptyString(email)}
Mobile: ${formatEmptyString(mobile)}
Message:
${message}
----`;
const cfMessage = new EmailMessage(
"contact@michaelpivato.dev",
"contact@michaelpivato.dev",
rawEmailMessage
);
try {
await (context.env as any).SEB.send(cfMessage);
const rawEmailMessage = `----
From: Michael Pivato Contact Form <contact@michaelpivato.dev>
To: Michael Pivato <contact@michaelpivato.dev
Subject: Message from ${fullName ?? email}
You've received a new message from ${fullName ?? email}.
Full Name: ${formatEmptyString(fullName)}
Organisation: ${formatEmptyString(organisation)}
Email: ${formatEmptyString(email)}
Mobile: ${formatEmptyString(mobile)}
Message:
${message}
----`;
await context.env.SERVICE.sendEmail(rawEmailMessage);
} catch (e) {
return new Response(e.message);
return new Response(e);
}
console.log("Full Name: " + fullName ?? "fullname");
console.log("Organisation: " + organisation);
console.log("Email: " + email ?? "email");
console.log("Mobile: " + mobile ?? "mobile");
console.log("Message: " + message);
}
return Response.redirect("https://michaelpivato.dev");