1

I'm trying to add EmailJS reCaptcha verification in my code. I have read the documentation but I can't understand how to apply it and I haven't found any examples.

function Register() {

    const [open, setOpen] = useState(false);

    const [toSend, setToSend, ] = useState({
        azienda: '',
        email: '',
        piva: '',
        codicefiscale: '',
    });

    const handleSubmit=(e)=>{
        e.preventDefault();
        send(
            'service_****',
            'template_*****',
            toSend,
            '************',
            'g-recaptcha-response'
        )
            .then((response) => {
                setOpen(true);
            })
    };

    const handleChange = (e) => {
        setToSend({...toSend, [e.target.name]: e.target.value });
    };

above the submit button in the form:

<ReCAPTCHA       
 sitekey='**********'
/>

I got this error when I submit the form:

enter image description here

Adele
  • 259
  • 1
  • 4
  • 11

2 Answers2

0

I faced this same issue and was able to overcome that.

Here is what you need to do in order to successfully send emails with the EmailJS Recaptcha (V2) Setting enabled:

  • In your code add a useRef hook to the captcha. I am naming it refCaptcha in the example below (don't forget to import useRef from 'react'.
  • Add ref={refCaptcha} in your <ReCAPTCHA /> component (see below).
  • Inside your handleSubmit() function, below the e.preventDefault() you must get the value from the captcha, you can do it like this refCaptcha.current.getValue();, see in the example below how I saved it to this token const.
  • Then you have to create this object, I named it params and spreaded your toSend state on it and added 'g-recaptcha-response': token to it, see in the example below.
  • And then inside your emailjs.send() method, you add the params object we just created as the third parameter instead of your toSend state directly, again check it in the example below.
function Register() {

    const refCaptcha = useRef(); // <- add the useRef hook

    const [open, setOpen] = useState(false);

    const [toSend, setToSend, ] = useState({
        azienda: '',
        email: '',
        piva: '',
        codicefiscale: '',
    });

    const handleSubmit=(e)=>{
        e.preventDefault();
    
        const token = refCaptcha.current.getValue(); // <- `getValue()` from the instantiated refCaptcha
    
        const params = {
          ...toSend,
          'g-recaptcha-response': token,
        }; // <- Create this object spreading your state and adding the retrieved token as a value of 'g-recaptcha-response'
    
        emailjs.send(
            'service_****',
            'template_*****',
            params, // <- Replace your state with this params object that contains the g-recaptcha-response key/value with the token retrieved.
            '************',
            'g-recaptcha-response'
        )
            .then((response) => {
                setOpen(true);
            },
            (err) => {
              console.log('EMAILJS ERROR', err);
            })
    };

    const handleChange = (e) => {
        setToSend({...toSend, [e.target.name]: e.target.value });
    };
    return (

        <form onSubmit={handleSubmit}>
          ...
        <ReCAPTCHA ref={refCaptcha} sitekey={process.env.REACT_APP_SITE_KEY} />
        // add the ^^ `ref={refCaptcha}` into your ReCAPTCHA component
        </form>
    )
  };

I just tested here and was able to send an email using EmailJS with Recaptcha (V2) enabled doing the steps outlined above.

Some sources where I was able to gather the bits and pieces to solve this (there is no solution in these links, just little pieces that lead to this solution):

Thiago Bernardi
  • 108
  • 1
  • 8
0

I'm not sure if my answer applies to this question since I used the invisible ReCaptcha. But I had the exact same error message and ended up here to find the answer. In my case, because of the invisible property the website user didn't prompt the captcha verification by clicking 'I'm not a robot', so it was necessary to programmatically execute the captcha to get the token. I came up with the following solution.

  const Form = () => {
    //form answers are saved as templateParams
    const [templateParams, setTemplateParams] = useState({
      azienda: '',
      email: '',
      piva: '',
      codicefiscale: '',});
      //reference to recaptcha
      const recaptchaRef = React.useRef<ReCAPTCHA>(null);

      //setting the form params on input change     
      const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setTemplateParams({...templateParams, [e.taget.name]: e.target.value});
      }
      
     const submitInput = (token) => {} //see declaration below

     //executing captcha on formsubmit
     const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
       e.preventDefault();
       const token = await recaptchaRef.current.executeAsync(); //executeAsync executes the captcha and awaits the result if user input is required. 
       token && submitInput(token); //when the token is ready, the actual submit function is called

      return (
        <form onSubmit={handleSubmit}>
          <ReCAPTCHA
            ref={recaptchaRef}
            size="invisible" //removing the 'I'm not a robot' box
            sitekey={process.env.PUBLICRECAPTCHAKEY}
          <input name='azienda' onChange={handleChange} />
          ...
        </form>
        )
    }

The form data has been saved in state and the captcha has been executed - meaning that if there is suspicious behaviour, the user is asked to complete the puzzle. Once the token is available, the following function is called:

  const submitInput = (token: string | null) => {
    const params = {
      ...templateParams,
      'g-recaptcha-response': token
  }
  emailjs.send(
    'your_service_name',
    'your_template_name',
    params,
    'g-recaptcha-response': token
    )
    .then(() => {
      recaptchaRef.current.reset(); // resetting captcha so it has to be completed again before sending a new message
    }, err => {
    console.error(err)
    //and inform the user that submission failed
  }
  }
Moira
  • 56
  • 6