DEV Community

yash kumat
yash kumat

Posted on

Contact from - send Email directly from client-side

A contact form let visitors fill out the form and submit it to send a message to the site owner

Behind the scenes, your contact form triggers an emails.sendForm() function which generate email message and send it to your mail id.

emailjs.sendForm(
    'YOUR_SERVICE_ID', 
    'YOUR_TEMPLATE_ID', 
    form.current, 
    'YOUR_USER_ID'
).then((result) => {},(error)=>{})
Enter fullscreen mode Exit fullscreen mode

Steps

1 . Create account on EmailJS

2 . Add new email service

Image description

3 . Add new template
edit template as per your requirement
Image description

Image description

4 . create react app

$ npx create-react-app project_name
Enter fullscreen mode Exit fullscreen mode

5 . Install EmailJS library

$ npm install @emailjs/browser --save
Enter fullscreen mode Exit fullscreen mode

6 . Create contact form

<form ref={form} onSubmit={sendMail} className='contact-form'>
   <input type="text" className="form-input" name="name"  placeholder='your name'/>
   <input type="text" className="form-input" name="subject" placeholder='subject' />
   <input type="email" className="form-input" name="email" placeholder='youremail' />
   <input type="message" className="form-input" name="message" placeholder='message' />
   <input type="submit" className='form-button' value="Send Mail" />
</form>
Enter fullscreen mode Exit fullscreen mode

useRef() hook
Note - The useRef is a hook that allows to directly create a reference to the DOM element in the functional component.

const form = useRef();
console.log(form.current)
Enter fullscreen mode Exit fullscreen mode

Result -

[Log] <form class="contact-form">
<input type="text" class="form-input" name="name" placeholder="your name">
<input type="text" class="form-input" name="subject" placeholder="subject">
<input type="email" class="form-input" name="email" placeholder="youremail">
<input type="message" class="form-input" name="message" placeholder="message">
<input type="submit" class="form-button" value="Send Mail">
</form>
Enter fullscreen mode Exit fullscreen mode

7 . Now call emailjs.sendForm()

emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_USER_ID')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
Enter fullscreen mode Exit fullscreen mode

This function generate email message and send it to your mail id.

Discussion (0)