Can't Send Email

Hi, I created a React Web Protfolio and my site contains contact form. Which is for the give access to users to send me emails. I tried multiple things and can’t figure that out. Here is my GitHub repo: https://github.com/gorkemtand/Portfolio

netlify.toml:

[build]
  functions = "functions"

[[redirects]]
    from = "/*"
    to = "/index.html"
    status = 200

sendEmail.js:

const sgMail = require('@sendgrid/mail');

exports.handler = async (event, context) => {
  console.log("Executing email.js");
  try {
    const { name, email, message } = JSON.parse(event.body);

    // Set up SendGrid API key
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);

    // Compose the email
    const msg = {
      to: process.env.CONTACT_EMAIL, // Replace with your email address
      from: email,
      subject: 'New Contact Form Submission',
      text: `Name: ${name}\nEmail: ${email}\n\nMessage: ${message}`,
    };

    // Send the email
    await sgMail.send(msg);
    console.log(process.env.SENDGRID_API_KEY);
    console.log(process.env.CONTACT_EMAIL);
    return {
      statusCode: 200,
      body: 'Email sent successfully',
    };
  } catch (error) {
    console.log('Error sending email:', error);

    return {
      statusCode: 500,
      body: 'An error occurred while sending the email',
    };
  }
};

ContactForm.jsx:

import React, { useState } from "react";
import swal from "sweetalert";

function ContactForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    subject: "",
    message: "",
  });

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
  
    try {
      const response = await fetch("/contact", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });
  
      if (response.ok) {
        const responseData = await response.json();
        console.log(responseData);
        setFormData({
          name: "",
          email: "",
          subject: "",
          message: "",
        });
        swal("Email successfully sent!", "", "success");
      } else {
        swal("Error sending email", "", "error");
        console.error("Error sending email:", response.status);
      }
    } catch (error) {
      swal("Error sending email", "", "error");
      console.error("Error sending email:", error);
    }
  };
  

  return (
    <form name="contact" action="/contact" method="post" className="contactForm" onSubmit={handleSubmit}>
    <input type="hidden" name="form-name" value="contact" />
      <div className="formDiv">
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          autoComplete="on"
          required
        />
      </div>
      <div className="formDiv">
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          autoComplete="on"
          required
        />
      </div>
      <div className="formDiv">
        <label htmlFor="subject">Subject:</label>
        <input
          type="text"
          id="subject"
          name="subject"
          value={formData.subject}
          onChange={handleChange}
          required
        />
      </div>
      <div className="formDiv">
        <label htmlFor="message">Message:</label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          required
        />
      </div>
      <button type="submit">Send Email</button>
    </form>
  );
}

export default ContactForm;

The error I got:

Please help me.

/contact should be replaced with /.netlify/functions/sendEmail

1 Like


This is my path should it be like that or do I need modifications?

You just need to make the exact change in your code that I’ve mentioned. No more, no less.

There: Update ContactForm.jsx by Hrishikesh-K · Pull Request #1 · gorkemtand/Portfolio (github.com) submitted a PR

1 Like

Made the changes and now i got this error:

Check the logs here: Function details | Functions | storied-cupcake-0a89a8 | Netlify

You haven’t added your environment variables:

1 Like

I actually add them here:

And also i have them in my .env file too:

You also need to trigger a deploy after adding the variables.

1 Like

How can i trigger it?

Deploys | storied-cupcake-0a89a8 | Netlify

You can choose any option from the drop-down.

Feel free to reject my deploy request for the previous PR.

1 Like

Looks like it worked.

1 Like

Actually, i got the emails but:

That’s because you’re returning text data:

but parsing it as JSON.

Either change await response.json() to await response.text() OR change:

return {
  statusCode: 200,
  body: 'Email sent successfully',
};

to

return {
  statusCode: 200,
  body: JSON.stringify({message: 'Email sent successfully'}),
};
1 Like

You are a true legend! I can’t thank you enough. I was trying to do that for two days. Thank you very much. Indeed I have one more question. I have a domain name if I change the domain name it won’t break the site and emailing function right?

Nope, nothing should break with the emails.

1 Like

Can I ask you something? In this format if only the email input is filled with my email works. When I try to write another email to the input field it gives error. Everyone should be able to send me emails, that is the point of the form. Do you know how can I fix it? In SendGrid I have Single Sender Verification, can it be the problem?

You should start checking your function logs:

Sendgrid is returning a 403. Why? That only Sengrid can answer, or you can try loggied the body of that error.

In this code, you’re asking Sendgrid to send the email from the email address entered in the form. I don’t think Sendgrid will allow that. But, you can confirm that with them.