skip to Main Content

When i am trying to send a message using React with above code:

import emailjs from '@emailjs/browser'
const sendEmail = (e) => {
        e.preventDefault();

        emailjs.sendForm('gmail', 'service_*', form.current, 'template_*','public key', )
        .then(
            () => {
            alert('Message successfully sent!');
            window.location.reload(false)
        }, (error) => {
            console.error('Failed to send the message:', error);
            alert(`Failed to send the message: ${error.text}`);
        });
    };

I got the message "Failed to send the message: The Public Key is invalid.

Tying to refresh the Public key and edit the code just like this:

const sendEmail = {
  name: 'James',
  notes: 'Check this out!',
};

emailjs
  .send('SERVICE_ID', 'TEMPLATE_ID', sendEmail, {
    publicKey: 'PUBLIC_KEY',
  })
  .then(
    (response) => {
      console.log('SUCCESS!', response.status, response.text);
    },
    (err) => {
      console.log('FAILED...', err);
    },
  );

2

Answers


  1. Chosen as BEST ANSWER

    Solved! Attached the sendEmail function to an event and used e.preventDefault() to prevent the default form submission behavior:

    emailjs.init({ publicKey: '*' }); 
    

    const sendEmail = (e) => { e.preventDefault();

    var emailData = {
        name: 'Konstantinos Iakovou | Web developer',
        notes: 'Check this out!',
    };
    
    emailjs.send('service_*', 'template_*', emailData).then(
        (response) => {
            alert('Message successfully sent!');
        },
        (error) => {
            console.error('Failed to send the message:', error);
            alert(`Failed to send the message: ${error.text}`);
        },
    );
    

    };


  2. If you need to send email using the Gmail service, you need to obtain an application password. Get yourself a key from https://support.google.com/accounts/answer/185833 and try the operations again after inserting it into your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search