使用 Nextjs TypeScript 和 NodeMailer 将联系信息发送到 Gmail 时出错

问题描述 投票:0回答:1

我能够获取数据并发送电子邮件,但无法发送包含数据的电子邮件。

这是我的表单代码:

"use client"
import React, { useState } from 'react';

const SplitContactForm: React.FC = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');
  const [status, setStatus] = useState('');

  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value);
  };

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
  };

  const handleMessageChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setMessage(e.target.value);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // Send form data to server-side email handler
    const formData = {
      name,
      email,
      message,
    };
    console.log(formData)

    try {
      const response = await fetch('/api/contactform', {
        method: "POST",
        body: JSON.stringify(formData),
        headers: {
          'Content-Type': 'application/json',
        }
      })
      if (!response.ok) {
        throw new Error('HTTP error! status: ' + response.status);
      }
      const responseData = await response.json()
      console.log("ResponseData: ", responseData)
      console.log("RESPONSE: ", response)

    } catch (error: ERROR) {
      console.log("Problem with the fetch operation" + error.message)
    }

    // Clear form inputs
    setName('');
    setEmail('');
    setMessage('');
  };

  return (
    <div className="flex flex-col md:flex-row bg-red-500">
      <div className="w-full md:w-1/2 px-10 py-8 md:border-r">
        <h2 className="text-2xl font-bold mb-4 text-white">Payment Information</h2>
        {/* Payment method integration */}
        {/* Include the necessary fields and logic for payment integration */}
        <p className="mt-8">
          Comida For Familias, Inc. is readily available to have any speaking arrangements from a wide range of topics. Schedule an appearance with us today! If you plan to affiliate with us, describe in detail any activities that you have planned.
        </p>

        <div className="mt-8">
          <h3 className="text-lg font-semibold mb-2">Contact Information:</h3>
          <p className='flex align-middle text-justify py-2'>
            <svg xmlns="http://www.w3.org/2000/svg" height="1.5em" className='my-0 px-2' viewBox="0 0 384 512"><path d="M215.7 499.2C267 435 384 279.4 384 192C384 86 298 0 192 0S0 86 0 192c0 87.4 117 243 168.3 307.2c12.3 15.3 35.1 15.3 47.4 0zM192 128a64 64 0 1 1 0 128 64 64 0 1 1 0-128z" /></svg>
            131 Sunset Ave, Suite E, PMB 254, Suisun City, 94585, CA</p>

          <p className='flex align-middle text-justify py-2'>
            <svg xmlns="http://www.w3.org/2000/svg" height="1.2em" className='my-0 px-2' viewBox="0 0 512 512"><path d="M164.9 24.6c-7.7-18.6-28-28.5-47.4-23.2l-88 24C12.1 30.2 0 46 0 64C0 311.4 200.6 512 448 512c18 0 33.8-12.1 38.6-29.5l24-88c5.3-19.4-4.6-39.7-23.2-47.4l-96-40c-16.3-6.8-35.2-2.1-46.3 11.6L304.7 368C234.3 334.7 177.3 277.7 144 207.3L193.3 167c13.7-11.2 18.4-30 11.6-46.3l-40-96z" /></svg>
            707-716-9325
          </p>
          <p className='flex align-middle text-justify py-2'>
            <svg xmlns="http://www.w3.org/2000/svg" height="1.2em" className='my-0 px-2' viewBox="0 0 512 512"><path d="M48 64C21.5 64 0 85.5 0 112c0 15.1 7.1 29.3 19.2 38.4L236.8 313.6c11.4 8.5 27 8.5 38.4 0L492.8 150.4c12.1-9.1 19.2-23.3 19.2-38.4c0-26.5-21.5-48-48-48H48zM0 176V384c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V176L294.4 339.2c-22.8 17.1-54 17.1-76.8 0L0 176z" /></svg>
            [email protected]
          </p>
        </div>
      </div>
      <div className="w-full md:w-1/2 px-4 py-8">
        <h2 className="text-2xl font-bold mb-4">Contact Information</h2>
        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label htmlFor="name" className="block text-gray-700">
              Name
            </label>
            <input
              type="text"
              id="name"
              className="border rounded py-2 px-3 w-full"
              value={name}
              onChange={handleNameChange}
              required
            />
          </div>
          <div className="mb-4">
            <label htmlFor="email" className="block text-gray-700">
              Email
            </label>
            <input
              type="email"
              id="email"
              className="border rounded py-2 px-3 w-full"
              value={email}
              onChange={handleEmailChange}
              required
            />
          </div>
          <div className="mb-4">
            <label htmlFor="message" className="block text-gray-700">
              Message
            </label>
            <textarea
              id="message"
              className="border rounded py-2 px-3 w-full h-32"
              value={message}
              onChange={handleMessageChange}
              required
            ></textarea>
          </div>
          <button
            type="submit"
            className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded"
          >
            Submit
          </button>
        </form>
      </div>

    </div>
  );
};

export default SplitContactForm;

这是我的 api/contactform/route.tsx 代码:

import { NextApiRequest, NextApiResponse } from 'next';
import nodemailer from 'nodemailer';

export async function POST(req: NextApiRequest, res: NextApiResponse) {
  console.log('DATA', req.body)

  console.log("THIS IS REQUEST METHOD: ", req.method)


  if (req.method === 'POST') {
    const { name, email, message } = req.body;

    // Create a transporter object with Gmail SMTP settings
    const transporter = nodemailer.createTransport({
      service: process.env.EMAIL_SERVICE_PROVIDER,
      port: 465,
      secure: true,
      auth: {
        user: process.env.EMAIL_ADDRESS,
        pass: process.env.EMAIL_PASSWORD,
      },
    });

    // Define the email options
    const mailOptions = {
      from: process.env.EMAIL_ADDRESS,
      to: process.env.DESTINATION_EMAIL_ADDRESS,
      subject: 'New Contact Form Submission',
      text: `
        Name: ${name}
        Email: ${email}
        Message: ${message}
      `
    };

    // Send the email using the transporter object
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.error('Error:', error);
        res.status(500).json({ success: false, error: 'Failed to send email' });
      } else {
        console.log('Email sent:', info.response);
        res.json({ success: true });
      }
    });
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

每次运行它时,我都会收到 500 错误和“错误 TypeError:无法读取未定义的属性(读取“标头”)”。但至少我收到一封带有未定义属性的电子邮件。

我安装了nodemailer,并尝试更改next.config.js文件的配置。

typescript email next.js nodemailer
1个回答
0
投票

兄弟我也面临着同样的问题。我们的代码几乎相同,只是我使用的是 axios。

© www.soinside.com 2019 - 2024. All rights reserved.