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
Solved! Attached the sendEmail function to an event and used e.preventDefault() to prevent the default form submission behavior:
const sendEmail = (e) => { e.preventDefault();
};
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.