使用nodemailer发送电子邮件,并将表单数据插入mysql db

时间:2019-06-27 00:26:51

标签: mysql node.js express post nodemailer

尝试设置一个表单,以接收用户输入的Beta测试电子邮件列表,该表单将向我发送一封包含用户信息的电子邮件,并将相同的表单数据存储到mysql数据库中。

我在与nodemailer对象相同的路由内具有mysql连接和查询,但是在提交表单时出现错误,提示“未定义管理员”。这是运输对象内部的管理员。我以为如果两个不同的对象(传输器和连接)具有相同的属性名称,可能会导致问题,因此我将传输器内部的常规nodemailer'user'更改为'admin'。

const express = require("express");
const app = express();
const nodemailer = require("nodemailer");
const bodyParser = require("body-parser");
const mysql = require("mysql");

app.use(bodyParser.urlencoded({extended: true}));

// send "Beta" email when user signs up to the email list using the "Beta" form
app.post("/register", function(req, res){
    // connect to database
    const connection = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "PASSWORD",
        database: "DATABASE_NAME"
    });

    // insert statement
    let insert = "INSERT INTO Beta_Testers(First_Name, Last_Name, Beta_Email) VALUES ('" + req.body.First_Name + "', '" + req.body.Last_Name + "', '" + req.body.Beta_Email + "')";

    // execute the insert statement
    connection.query(insert);

    // disconnect from database
    connection.end();

    // nodemailer objects
    let mailOpts, transporter;

    // email transporter
    transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 3000, // changed from 465
        secure: true,
        auth: {
            admin: "GMAIL_USER",
            pass: "PASSWORD"
        }
    });

    // email credentials
    mailOpts = {
        from: req.body.First_Name + " " + req.body.Last_Name + " <" + req.body.Beta_Email + ">",
        to: admin,
        subject: "You have a new BETA tester!",
        text: `${req.body.Beta_Email} has signed up to be a BETA tester for WEBAPP_NAME. Please confirm sucessful registration into DATABASE_NAME.`
    };

    // send email and verify contact
    transporter.sendMail(mailOpts, function(err, res) {
       if (err) {
           res.render("contact-failure");
       } else {
           res.render("contact-success");
       }
    });
});
ReferenceError: admin is not defined

1 个答案:

答案 0 :(得分:0)

该错误位于:“至:admin”

它应包含将向其发送电子邮件的电子邮件。这些是mail_options,需要使用诸如“ abc@xyz.com”之类的电子邮件来设置选项“ to”。

您可以设置:-

收件人:req.body.email