DEV Community

otowa552
otowa552

Posted on

How to send emails using Contact Form 7 API

Due to the change in the CF7 specification, it is (probably) not possible to send emails with the CF7API by any method currently available on the Internet.

I would like to write how to do it for people like me who have to create a mail form with Wordpress in 2024.

Here is a simple example.

  • HTML
<form id="Form">
  <dl>
    <dt>Name</dt>
    <dd><input type="text" name="your-name"></dd>
    <dt>Email</dt>
    <dd><input type="text" name="your-email"></dd>
    <dt>Subject</dt>
    <dd><input type="text" name="your-subject"></dd>
    <dt>Message</dt>
    <dd><textarea name="your-message"></textarea></dd>
  </dl>
  <input type="submit" value="Submit">
</form>
Enter fullscreen mode Exit fullscreen mode
  • JS
const Form = document.querySelector("Form");

Form.addEventListener("submit", async (e) => {
    e.preventDefault();

    const formData = new FormData(Form);
    formData.append("_wpcf7_unit_tag", "<CF7_UNIT_TAG>");

    try {
        const response = await fetch(
            "https://your.site/wp-json/contact-form-7/v1/contact-forms/<CF7_FORM_ID>/feedback",
            {
                method: "POST",
                headers: {
                    "Content-Type": "amultipart/form-data",
                },
                body: formData,
            },
        );

        console.log(response);
    } catch (error) {
        console.error(error);
    }
});
Enter fullscreen mode Exit fullscreen mode
  • CF7 Edit Page
<label> Your name
    [text* your-name autocomplete:name] </label>

<label> Your email
    [email* your-email autocomplete:email] </label>

<label> Subject
    [text* your-subject] </label>

<label> Your message (optional)
    [textarea your-message] </label>

[submit "Submit"]
Enter fullscreen mode Exit fullscreen mode

The point is to add a unit tag to the form content.
Due to the change in CF7 specifications, the id attribute of the shortcode now includes a unit tag.

[contact-form-7 id="<CF7_UNIT_TAG>" title="Contact form 1"]
Enter fullscreen mode Exit fullscreen mode

I don't know how to get the ID other than looking at the URL of the CF7 Edit Page.(If you know, please tell me in the comments.)

https://your.site/wp-admin/admin.php?page=wpcf7&post=<CF7_FORM_ID>&action=edit
Enter fullscreen mode Exit fullscreen mode

It's easier to use AlpineJS or something to make complex forms. It might also be good to partially introduce React or Vue.
Using CF7 with API will make the backend easier.
If it was helpful, please let me know in the comments.

Top comments (0)