ReactJS Nodemailer 不发送电子邮件

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

尝试弄清楚如何使用 ReactJS 和 Nodemailer 发送电子邮件。

在我的客户端文件夹中,我有 App.js,如下所示:

import "./App.css";
import { useState } from "react";
import axios from "axios";

function App() {
  const [email, setEmail] = useState();
  const [subject, setSubject] = useState();
  const [message, setMessage] = useState();

  const sendMail = () => {
    axios
      .get("http://localhost:4000", {
        params: {
          email,
          subject,
          message,
        },
      })
      .then(() => {
        console.log("success");
      })
      .catch(() => {
        console.log("failure");
      });
  };

  return (
    <div>
      <input
        type="text"
        onChange={(e) => setEmail(e.target.value)}
      />
      // 2 more inputs for subject and message
      <button onClick={sendMail}>Submit</button>
    </div>
  );
}
export default App;

在我的服务器文件夹中,我有一个名为 app.js 的文件,如下所示:

const express = require("express");
const nodemailer = require("nodemailer");
const cors = require("cors");
const app = express();
const port = 4000;

app.use(cors());
app.use(express.json({ limit: "25mb" }));
app.use(express.urlencoded({ limit: "25mb" }));
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  next();
});

function sendEmail({ email, subject, message }) {
  return new Promise((resolve, reject) => {
    var transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: "[email protected]",
        pass: "google app password",
      },
    });

    const mail_configs = {
      from: "[email protected]",
      to: email,
      subject: subject,
      text: message,
    };

    transporter.sendMail(mail_configs, function (error, info) {
      if (error) {
        console.log(error);
        return reject({ message: `An error occurred.` });
      }

      return resolve({ message: "Email sent successfully" });
    });
  });
}

app.get("/", (req, res) => {
  sendEmail(req.query)
    .then((response) => response.send(response.message))
    .catch((error) => res.status(500).send(error.message));
});

app.listen(port, () => {
  console.log(`nodemailer is listening at http://localhost:${port}`);
});

运行代码后,我在控制台中收到“失败”消息以及 500 错误。 这是整个错误的屏幕截图:

enter image description here

我在这里发现的一个问题指出,我需要在我的 Google 帐户上启用不太安全的应用程序功能,但我的帐户似乎没有该选项:

enter image description here

我做错了什么以及如何解决它?

reactjs node.js nodemailer mailer
1个回答
0
投票

我认为您的邮件配置缺少文档中所述的主机和端口https://nodemailer.com/about

const transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 587,
  secure: false, // Use `true` for port 465, `false` for all other ports
  auth: {
    user: "[email protected]",
    pass: "appPassword",
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.