16

i have a single email input field and a button in my app. once i enter the email and click send i would like to send an email with the value entered in the input. i know it cant be done in Reactjs because it is a frontend. How can i do? can someone help?

2
  • Since you tagged node.js, do you have a Node server running? Commented Apr 22, 2019 at 13:31
  • no i dont.... i thought a mail can be send using node.js... so i tagged it Commented Apr 22, 2019 at 13:32

4 Answers 4

37

From a front end client you can send a request to an SMTP server, which will send the email.

This tutorial runs over how to do that with the emailJS SMTP server, (which allows you to send 200 free emails/month in case free is a priority).

I'll summarize because they didn't cover everything I wanted.


Step1: Install emailJS

Install emailJS via

npm install @emailjs/browser

If you are using create-react-app please view the tutorial I mentioned above or this linked source, where they provide instructions on how to include emailJS with create-react-app

Step 2: Create a form to send the email

This is a code example of a form which sends an email using emailJS, You must replace 'YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', and 'YOUR_PUBLIC_KEY' with your actual id's(which I will explain where to find in later steps)

export default function EmailForm() {
  function sendEmail(e) {
    e.preventDefault(); // This is important, i'm not sure why, but the email won't send without it

    emailjs
      .send(
        'YOUR_SERVICE_ID',
        'YOUR_TEMPLATE_ID',
        {},
        {
          publicKey: 'YOUR_PUBLIC_KEY',
        }
      )
      .then(
        (result) => {
          alert('Email sent!');
          window.location.reload(); // This is if you still want the page to reload (since e.preventDefault() cancelled that behavior)
        },
        (error) => {
          console.log(error.text);
        }
      );
  }

  return (
    <form className="contact-form" onSubmit={sendEmail}>
      <input type="hidden" name="contact_number" />
      <label>Name</label>
      <input type="text" name="from_name" />
      <label>Email</label>
      <input type="email" name="from_email" />
      <label>Subject</label>
      <input type="text" name="subject" />
      <label>Message</label>
      <textarea name="html_message" />
      <input type="submit" value="Send" />
    </form>
  );
}

Source (I made some adjustments)

  • If you don't want your api details to be visible from the client, you would have to make a request (containing the email message, from, to, etc.) to a backend server(which would be set up and running to receive requests) via something like axios or fetch and then execute the sendEmail function from your server

Step 3: Create an emailJS account

Set up an account at https://www.emailjs.com/

Step 4: Connect an email account to emailJS and get YOUR_SERVICE_ID

Connect an email by adding a service (click the "Add a Service" button), in this case I used gmail.

'YOUR_SERVICE_ID'(step 2) should be the id beside Service ID

enter image description here

  • if you receive 412 Gmail_API: Request had insufficient authentication scopes, just delete the emailJS Gmail service on emailJS website and create a new one

Step 5: Create a template email message and get YOUR_TEMPLATE_ID

Create a a template by clicking Email Templates in the side nav and selecting create new template. This will create an email outline and give you a template id

You should replace 'YOUR_TEMPLATE_ID'(step 2) with this template id

enter image description here

Here is an example Email template

enter image description here

Step 6: Get YOUR_USER_ID

You can find your publicKey by going to Account on the left side menu (stay on the General tab)

Replace 'YOUR_PUBLIC_KEY'(step 2) with the id under API Keys -> Public Key

enter image description here


  • If you don't want spam emails, add Captcha

  • if you change your email password, you have to redo step 4

-----------------

Here's a working stackblitz: https://stackblitz.com/edit/vitejs-vite-jqpfquug?file=src%2FEmailForm.jsx,src%2FApp.jsx,src%2Findex.css&terminal=dev

Sign up to request clarification or add additional context in comments.

5 Comments

Good explanation and its works for me, I think they made some changes inside the API, they will change OUR_USER_ID to Public Key and you can to found it inside Account > API Keys > Public Key
This is a phenomenal explanation. Much props to you sir! I am curious how you obtained all this information though. I probably didn't take enough time to navigate the docs but nothing I found was as simple and accurate as this. Thank you again!
This is working fine but it is loading the whole page in react js. i think this line not required. window.location.reload()
Thanks Sam for the detailed explanation. It seems emailjs-com is deprecated, and emailjs/browser is used instead. Follow the emailjs docs for the updated code example.
Updated my answer to @emailjs/browser
8

From frontend only you can trigger mails using an smtp server such as smtpJS

Steps to follow is

  1. Go to this link smtpJS
  2. Click GetSMTPCredentials and register.
  3. After registering, note down the credentials and click ENCRYPTSMTPCrendentials

A sample would be as follows

var test={
sendEmail(subject,to,body){
    
    /* SmtpJS.com - v3.0.0 */
    let Email = { send: function (a) { return new Promise(function (n, e) { a.nocache = Math.floor(1e6 * Math.random() + 1), a.Action = "Send"; var t = JSON.stringify(a); Email.ajaxPost("https://smtpjs.com/v3/smtpjs.aspx?", t, function (e) { n(e) }) }) }, ajaxPost: function (e, n, t) { var a = Email.createCORSRequest("POST", e); a.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), a.onload = function () { var e = a.responseText; null != t && t(e) }, a.send(n) }, ajax: function (e, n) { var t = Email.createCORSRequest("GET", e); t.onload = function () { var e = t.responseText; null != n && n(e) }, t.send() }, createCORSRequest: function (e, n) { var t = new XMLHttpRequest; return "withCredentials" in t ? t.open(e, n, !0) : "undefined" != typeof XDomainRequest ? (t = new XDomainRequest).open(e, n) : t = null, t } };

    Email.send({
        SecureToken : process.env.SECURE_TOKEN, // write your secure token
        To : to, // to include multiple emails you need to mention an array
        From : process.env.EMAIL_HOST,
        Subject : subject,
        Body : body
    })
    .then(message=>{
        // alert(message);
    });

    
}
}

 export default test;

you can import above js file like below and call the method

import test from '../../components/sendEmail'
test.sendEmail("sub","msg");

1 Comment

It shows syntax error for me, any advice to solve?
0

React is only used for front end purpose so it is not only enough to send email.

But you can send email from client usingsome external API, like Mailjet, Gmail Api etc

Comments

0

Look this out Setting Email without a back end

its more handy and gives you all the control

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.