Cloudflare Email Worker via HTML form

123 views Asked by At

I'm having difficulty time trying to configure a HTML form to actually post an email to a worker node.

I've tried to follow the cloudflare documentation and github such as : https://github.com/maggie-j-liu/mail/tree/main

The HTML code as per below

 <form action="/api/email" method="POST">
      <div class="input-wrapper position-relative">
        <input id ="email" type="email" name="email" class="newsletter-form" id="newsletter" placeholder="Enter your email">
        <button type="submit" value="Submit" name="submit" class="btn newsletter-btn">Contact Us</button>
      </div>
    </form>

The code of the javascript aka the worker

// src/index.ts
var src_default = {
  async fetch(request, env) {
    console.log(env.DKIM_PRIVATE_KEY);
    let send_request = new Request("https://api.mailchannels.net/tx/v1/send", {
      method: "POST",
      headers: {
        "content-type": "application/json"
      },
      body: JSON.stringify({
        personalizations: [
          {
            to: [
              {
                email: "[email protected]"
                // add your to email here
              }
            ],
            dkim_domain: "domain.com",
            dkim_selector: "mailchannels",
            dkim_private_key: env.DKIM_PRIVATE_KEY
          }
        ],
        from: {
          email: "[email protected]"
          // add your from email here
        },
        subject: "Subject",
        content: [
          {
            type: "text/plain",
            value: "message"
          }
        ]
      })
    });
    let respContent = "";
    if (request.method == "POST") {
      const resp = await fetch(send_request);
      const respText = await resp.text();
      respContent = resp.status + " " + resp.statusText + "\n\n" + respText;
    }
    let htmlContent = `<html><head></head><body><p>Click to send message: <form method="post"><input type="submit" value="Send"/></form></p><pre>${respContent}</pre></body></html>`;
    return new Response(htmlContent, {
      headers: { "content-type": "text/html" }
    });
  }
};
export {
  src_default as default
};

There are two problem i'm facing at the moment:

1 - The first error when i try to do quick edit via cloudflare but wasn't recommended by others to test:

400 Bad Request

{"errors":["bad request - DKIM public key and private key mismatch: fail to decode private key in base64 format"]}

But i've verified this has no issue from https://www.mail-tester.com/spf-dkim-check

and verified the steps from https://support.mailchannels.com/hc/en-us/articles/7122849237389

2 - When i try with the POST using post form to /api/email, i get the following error

HTTP ERROR 405

Not sure where i'm going wrong, I'm still stuck trying to configure a static HTML page to send email.. Anyone has accomplished it using cloudflare?

0

There are 0 answers