Getting "undefined" returns using nodemailer with a form

26 Views Asked by At

I've tried looking at the answers on other similar questions, but no fixes have seemed to help. I don't know what I'm doing wrong. This is my first time making a website and using Next.js, and basically every tool used in the project. Followed two tutorials on YT, on for the general website, another for the forms. Appreciate any help.

The problem: I have two form side by side on the website. One is a contact form where you enter your personal info, and an optional message. The other is a form that allows the customer to send in pictures and ask for a price for a plumbing job. The contact form is sent perfectly, all data intact. The price form sends the data as "undefined" and doesn't send the uploaded pictures.

The code in question (the price form), named "TilbudForm.tsx":

    "use client";
    import { useState } from "react";
    export default function TilbudForm() {
    const [loading, setLoading] = useState(false);

    async function handleSubmit(event: any) {
        event.preventDefault();
        setLoading(true);
      
        const formData = new FormData();
        formData.append('tilbudNavn', event.target.tilbudNavn.value);
        formData.append('tilbudEmail', event.target.tilbudEmail.value);
        formData.append('tilbudTelefon', event.target.tilbudTelefon.value);
        formData.append('tilbud', event.target.tilbud.value);

        const billederFiles = event.target.billeder.files;
        if (billederFiles) {
            for (let i=0; i<billederFiles.length; i++) {
                formData.append('billeder', billederFiles[i]);
            }
        }

        try {
            const response = await fetch("/api/tilbud", {
                method: "POST",
                body: formData,
            });
    
            if (response.ok) {
                console.log("Message sent succesfully")
                setLoading(false)
                event.target.reset();
            } else {
                console.log("Error sending message")
                setLoading(false)
            }
        } catch (error) {
            console.error("Error sending mesage:", error);
            setLoading(false);
        }
      }


    return (
        <form className="mt-9" onSubmit={handleSubmit}>
            <div className="w-full flex flex-col bold-20 text-grey-30">
                <label htmlFor="tilbudNavn">Dit navn*</label>
                <input className="regular-18 text-grey-30 bg-zinc-200 p-4" type="text" autoComplete="off" id="tilbudNavn" required/>
            </div>

            <div className="w-full flex flex-col bold-20 text-grey-30">
                <label htmlFor="tilbudEmail">Din email*</label>
                <input className="regular-18 text-grey-30 bg-zinc-200 p-4" type="email" autoComplete="off" id="tilbudEmail"required/>
            </div>

            <div className="w-full flex flex-col bold-20 text-grey-30">
                <label htmlFor="tilbudTelefon">Dit telefonnummer*</label>
                <input className="regular-18 text-grey-30 bg-zinc-200 p-4" type="tel" autoComplete="off" id="tilbudTelefon"required/>
            </div>

            <div className="w-full flex flex-col bold-20 text-grey-3">
                <label htmlFor="billeder">Vedhæft gerne billeder</label>
                <input className="regular-18 text-grey-30 bg-zinc-200 p-4" type="file" autoComplete="off" id="billeder" multiple/>
            </div>

            <div className="w-full flex flex-col bold-20 text-grey-30">
                <label htmlFor="tilbud">Hvad skal du have et tilbud på?</label>
            </div>

            <textarea 
                rows={4}
                minLength={5}
                maxLength={500}
                name="tilbud"
                placeholder="Hvad skal du have et tilbud på?"
                className="w-full regular-18 text-gray-30 bg-zinc-200 p-4"
                required
            />
            
            <button 
            type="submit"
            disabled={loading} 
            className="px-4 py-2 w-50 mt-5 bg-zinc-600 disabled:bg-gray-400 disabled:text-gray-100 text-white font-medium">Indsend</button>
        </form>
    );
}

The api json, found in "api/tilbud.js":

import nodemailer from "nodemailer"

export default async function ContactAPI(req, res) {
    const {tilbudNavn, tilbudEmail, tilbudTelefon, tilbud} = req.body;
    const billeder = req.files?.billeder;

    const user = process.env.user

    const transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        port:465,
        secure: true,
        auth: {
            user: user,
            pass: process.env.pass,
        },
    });

    try {

        const mail = await transporter.sendMail({
            from: user,
            to: "[email protected]",
            replyTo: tilbudEmail,
            subject: `Tilbudsform. ${tilbudNavn} ønsker et tilbud.`,
            html:`
                <p>Navn: ${tilbudNavn}</p>
                <p>Email: ${tilbudEmail}</p>
                <p>Telefon: ${tilbudTelefon}</p>
                <p>Ønskede tilbud: ${tilbud}</p>
            `,
            attachments: billeder ? billeder.map(file => ({filename: file.name, content: file.data})) : []
        });

        console.log("Message sent:", mail.messageId);
        
        res.status(200).json({message: 'Message sent successfully!'})
    } catch (error) {
        console.log(error)
        res.status(500).json({
            message: "Could not send the email. Your message was not sent.",
        });
    }
}

This is the code I tried, made from the YT video I watched. But can't seem to figure out the problem, as I haven't worked with this before.

0

There are 0 best solutions below