This is a refactored version of the @cloudflare/pages-plugin-mailchannels plugin, which was based on the @cloudflare/pages-plugin-static-forms package.
Original package documentation from Cloudflare.
Added support for Cloudflare Turnstile.
Also fixed the bug that only returns 200 OK status codes.
npm i --save https://github.com/yhorian/pages-plugin-mailchannels
Copy the functions/_middleware.ts file from this repository over to the /functions folder of your own repository. Cloudflare will then parse this into a Function when the page is compiled. You also need to set "turnstile = true" if you're using turnstile and add your secret key as an environment variable named 'TURNSTILE_KEY' when installing the Turnstile code.
Don't forget to change the email inside the _middleware.ts to your own. It'll throw a 512:"Could not send your email. Please try again." error otherwise.
const myEmail = "example@example.com"
Once compiled by Cloudflare Pages, the Function will capture anything from a form with a 'data-static-form-name' attribute set, such as:
<body>
<h1>Contact us</h1>
<form data-static-form-name="contact">
<label>Name <input type="text" name="name" /></label>
<label>Email address <input type="email" name="email" /></label>
<label>Message <textarea name="message"></textarea></label>
<button type="Submit">
</form>
</body>
On form submit, you'll get an email from 'Contact form' with all the relevant data from the Mailchannel API. Some restrictions apply. A 512 error is generated every time the API rejects something as 'Spam'.
To use multiple middleware handlers or change the routes used, see this documentation on Chaining middleware.