我无法使用 Nodemailer 制作邮件系统

2 email node.js nodemailer

我已经创建这个系统几个小时了。我几乎要结束这个项目了,但不知怎的,我在填写表格后却收不到任何电子邮件。有谁知道这个问题的原因是什么?首先,我安装了node.js,然后安装了nodemon。我的项目文件夹中有四个主要文件和一个文件夹 - app.js、package-lock.json、contact.handlebars、package.json 和 node_module。

下面的代码是app.js

const express = require("express");
const bodyParser = require("body-parser");
const exphbs = require("express-handlebars");
const path = require("path");
const nodemailer = require("nodemailer");

const app = express();

// view engine setup
app.engine("handlebars", exphbs());
app.set("view engine", "handlebars");

// Static folder
app.use("/public", express.static(path.join(__dirname, "public")));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get("/", (req, res) => {
  res.render("contact", { layout: false });
});

app.post("/send", (req, res) => {
  const output = `
        <p>You have a new contact request</p>
        <h3>Contact Details</h3>
        <ul>
            <li>Name: ${req.body.name}</li>
            <li>Company: ${req.body.company}</li>
            <li>Email: ${req.body.email}</li>
            <li>Phone: ${req.body.phone}</li>
        </ul>
        <h3>Message</h3>
        <p>${req.body.message}</p>
    `;
  async function main() {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    let testAccount = await nodemailer.createTestAccount();

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: "I PUT 1ST SERVERNAME HERE OF HOSTGATOR",
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: "MY 1ST EMAIL ACCOUNT", // generated ethereal user
        pass: "********" // generated ethereal password
      },
      tls: {
        rejectUnauthorized: false
      }
    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: '"Nodemailer Contact" <MY 1ST EMAIL ACCOUNT>', // sender address
      to: "MY SECOND EMAIL ACCOUNT", // list of receivers
      subject: "Node Contact Request", // Subject line
      text: "Hello world?", // plain text body
      html: output // html body
    });

    console.log("Message sent: %s", info.messageId);
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

    res.render("contact", { layout: false }, { msg: "Email has been sent" });
  }

  main().catch(console.error);
});

app.listen(3000, () => console.log("server started..."));
Run Code Online (Sandbox Code Playgroud)

Hae*_*gin 5

Ethereal 的测试 SMTP 服务不发送电子邮件。从他们的网站:

这是一种完全免费的反交易电子邮件服务,消息永远不会被传递。

看起来它可以让您查看已发送邮件的预览,以检查您的应用程序是否正常工作,但要实际发送电子邮件,您需要设置一个真正的 SMTP 服务器。您可以获取 SMTP 凭据,用于从各个公司(例如 SendGrid 和 Mailgun)的应用程序发送事务邮件。