Amit Pandey
Amit Pandey

Reputation: 41

How to send email with ReactJS and SendGrid?

I have setup and account on SendGrid. I have got the API key and Node.js methods. I am creating an web app with React js. I want to send emails through SendGrid. I am unable to find any solution. Please help me with my question with an example.

Upvotes: 4

Views: 19652

Answers (4)

Hardik
Hardik

Reputation: 834

There are multiple solutions available.

  1. You could use nodeMailer : https://nodemailer.com/about/
  2. Node mailer even has transport dwritten specifically for Sendgrid : https://www.npmjs.com/package/nodemailer-sendgrid-transport
  3. You could use node package by sendgrid itself : https://github.com/sendgrid/sendgrid-nodejs/tree/main/packages/mail

Upvotes: 1

Anroche
Anroche

Reputation: 1011

You can use MailJS, and use sendgrid for transactional services. It's easy to use.

Upvotes: 1

Kumar
Kumar

Reputation: 324

Its not possible with react as it is a frontEnd library, if you try to implement with react you will get these errors

---> Refused to set unsafe header "User-Agent"

If you need to set those headers then you'll need to make the request from your server and not your visitor's browser.

So this is not possible from react and you will need to use some backend or firebase for it.

Upvotes: 4

Dickens
Dickens

Reputation: 33

//Form.js
class Form extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    fetch('/api/form-submit-url', {
      method: 'POST',
      body: data,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <label htmlFor="email">Enter your email</label>
        <input id="email" name="email" type="email" />

        <label htmlFor="birthdate">Enter your birth date</label>
        <input id="birthdate" name="birthdate" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}
//index.js

    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: [email protected]',
      from: '[email protected]',
      subject: 'Sending with SendGrid is Fun',
      text: 'and easy to do anywhere, even with Node.js',
      html: '<strong>and easy to do anywhere, even with Node.js</strong>',
    };

sgMail.send(msg);

Upvotes: 0

Related Questions