How to send form data with a file attachment to an email using React

To send form data with a file attachment via email using React.js, you’ll need a backend server to handle the email sending process. In this example, I’ll demonstrate the frontend part using React.js and assume you have a backend server set up to handle email sending (using technologies like Node.js and Nodemailer, for instance).

Create a React Component for the Form:

import React, { useState } from "react";

const EmailForm = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [file, setFile] = useState(null);

  const handleFileChange = (event) => {
    setFile(event.target.files[0]);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    // Prepare form data to be sent
    const formData = new FormData();
    formData.append("name", name);
    formData.append("email", email);
    formData.append("message", message);
    formData.append("file", file);

    try {
      // Send form data to the backend for email processing
      const response = await fetch("/api/sendEmail", {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        // Email sent successfully
        console.log("Email sent successfully!");
        // You may show a success message to the user or redirect to a thank-you page
      } else {
        // Error in sending email
        console.error("Failed to send email.");
        // You may show an error message to the user
      }
    } catch (error) {
      console.error("Error while sending the email:", error);
      // You may show an error message to the user
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>
      <div>
        <label htmlFor="message">Message:</label>
        <textarea
          id="message"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          required
        />
      </div>
      <div>
        <label htmlFor="file">File:</label>
        <input
          type="file"
          id="file"
          onChange={handleFileChange}
        />
      </div>
      <button type="submit">Send Email</button>
    </form>
  );
};

export default EmailForm;

Set up the backend to handle email sending (Node.js with Nodemailer):

Here’s a basic example of a Node.js backend using Nodemailer to send the email. You should have the necessary dependencies installed using npm install nodemailer express multer.

// server.js
const express = require("express");
const multer = require("multer");
const nodemailer = require("nodemailer");

const PORT = 5000;

const app = express();
const upload = multer();

// Replace with your actual email service credentials
const transporter = nodemailer.createTransport({
  service: "YourEmailService",
  auth: {
    user: "[email protected]",
    pass: "your-email-password",
  },
});

app.post("/api/sendEmail", upload.single("file"), async (req, res) => {

    const { name, email, message } = req.body;
    const file = req.file;

    // Prepare the email content
    const mailOptions = {
      from: "[email protected]",
      to: "[email protected]",
      subject: "New Email Form Submission",
      html: `<p>Name: ${name}</p><p>Email: ${email}</p><p>Message: ${message}</p>`,
      attachments: file ? [{ filename: file.originalname, content: file.buffer }] : [],
    };

    // Send the email
    await transporter.sendMail(mailOptions);
});

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

In this example, the React.js frontend captures the form data (name, email, message) and the selected file using the FormData API. It then sends this data to the backend server at /api/sendEmail using a POST request. The backend server processes the data and uses Nodemailer to send an email with the attached file (if provided).

Remember to replace "YourEmailService", "[email protected]", "your-email-password", and "[email protected]" with your actual email service information and desired recipient email address.

Please note that this is a basic example to illustrate the concept. In a production environment, you may want to add more error handling, validation, and security measures to ensure the form submission process is safe and reliable. Additionally, you might want to use environment variables to store sensitive information securely.

How to send form data with a file attachment to an email using React, video tutorial

1 thought on “How to send form data with a file attachment to an email using React”

  1. Pingback: How to send form data with a file attachment to an email address using React

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top