使用 EJS 模板时 Nodemailer 发送空白电子邮件

发布于 2025-01-16 07:45:06 字数 5495 浏览 2 评论 0原文

当启动页面上的提交按钮被点击时,我的服务器中的以下代码成功发送电子邮件。我正在提取来自 mongoDB 用户输入的列表。当我对变量数据调用 console.log 时,它显示一切都在正确的位置。这是我在终端中得到的内容,后面是代码本身。问题是,除了电子邮件正文为空白之外,一切看起来都正确。主题在那里,但控制台通过 ejs 以 html 形式打印的所有内容都消失了。终端说它在那里,但当我收到电子邮件时,空白......

DB CONNECTION SUCCESSFUL
Monday, March 21
Server is Flying
html data ======================> <body>

<h1></h1>
<ul>

    <li>Welcome to Fedex Staffing Beta!</li>

    <li>Geoffrey Singfred</li>

    <li>Elizabeth Holmes</li>

    <li>Diana Ross</li>

    <li>Frank</li>
  </ul>

</body>

[Error: 31772:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:
] {
  library: 'SSL routines',
  function: 'ssl3_get_record',
  reason: 'wrong version number',
  code: 'ESOCKET',
  command: 'CONN'
const express = require("express");
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
const date = require(__dirname + "/date.js");
const nodemailer = require("nodemailer");



// MONGO CONNECTION //
// This is the connection to the database. 27017 is the port mongo chooses by default

mongoose.connect("mongodb+srv://user-admin:[email protected]/cluster0?retryWrites=true&w=majority")

console.log("DB CONNECTION SUCCESSFUL")


// EE TABLE //
// This is the employee default schema. Just a name.
const itemsSchema = new mongoose.Schema ({
  item: String,
});

const listSchema = new mongoose.Schema({
  name: String,
  items: [itemsSchema]
});



// This initializes a new schema or what Mongo calls a collection. Each collection
// is essentially the equivalent of a table in SQL

const Item = mongoose.model("Item", itemsSchema);
const List = mongoose.model("List", listSchema);



// Write now the app starts with items by default. These are them. They can be deleted
// easily by checking the box in the app. I'm sure there is a better way to do this.

const item1 = new Item({
  item: "Welcome to Fedex Staffing!",
});


// Just a default list I use to call when a new page is created.

const defaultItems = [item1];


////// BEGIN APP //////

// Intitalize date
const day = date.getDate();

// Initialize express
const app = express();


// Initialize ejs
app.set("view engine", "ejs");
app.use(express.static("public"));


// Intialize body parser. 
app.use(bodyParser.urlencoded({
  extended: true
}));


// MAIN PAGE //


// A GET call to retrieve all current items in the database, if there are less
// than zero then it adds back the default items listed below
app.get("/", function(req, res) {

  Item.find({}, function(err, foundItems){ 

    if (foundItems.length === 0){
      Item.insertMany(defaultItems, function(err){
        if (err) {
          console.log(err);
        } else {
          console.log("Items successfully added.");
        }
      });
      res.redirect("/");
    } else {
      res.render("list", {listTitle: day,newListItems: foundItems});
    };
  });
});

// A POST call to add items to the list and the database
app.post("/", function(req, res) {


  const itemName = req.body.newItem;    
  const listName = req.body.list;      

  const item = new Item({
    item: itemName
  });

  if (listName === day){
    item.save();
    res.redirect("/");
  } else {
    List.findOne({name: listName}, function(err, foundList){  
      foundList.items.push(item);
      foundList.save();
      res.redirect("/" + listName);
    });
  };

});


// This delete route for when you check a checkbox, it then deletes the item. 

app.post("/delete", function(req, res){
  const checkedItemId = req.body.checkbox;
  const listName = req.body.listName;

  if (listName === day){
    Item.findByIdAndRemove(checkedItemId, function(err){ 
      if(!err) {
        console.log("Successfully deleted checked item")
        res.redirect("/");
      };
    });
  } else {
    List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
      if(!err){
        res.redirect("/" + listName);
      };
    });
  };

});

app.post("/send", function(req, res){
  const title = req.body.customName
  var transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 666,
      secure: true, // use SSL
      auth: {
          user: "***********@hellmail.com",
          pass: "*********"
      }
  });


  Item.find({}, function(err, foundItems){

  const data = ejs.renderFile(__dirname + "/views/emailtemp.ejs", {newListItems: foundItems, listTitle: title}, function (err, data) {
  if (err) {
      console.log(err);
  } else {
      var mainOptions = {
          from: '"Jesus"*************@gmail.com',
          to: "*********@gmail.com",
          subject: 'Hello, world',
          html: data
      };
      console.log("html data ======================>", mainOptions.html);
      transporter.sendMail(mainOptions, function (err, info) {
          if (err) {
              console.log(err);
          } else {
              console.log('Message sent: ' + info.response);
          }
      });
  }

  });
 });
});


console.log(day)


app.listen(process.env.PORT || 3000, function() {
  console.log("Server is Flying");
});
```

The following code in my server successfully sends an email when a submit button is hit on the splash page. I am pulling a list that is input from the user coming from mongoDB. When I call console.log on the variable data it shows that everything is in it's right place. This is what I get in the terminal, followed by the code itself. The problem is that everything looks correct except the emails are blank in the body. Subject is there but everything that the console is printing out in html through ejs is gone. Terminal says its there but when I receive email, blank...

DB CONNECTION SUCCESSFUL
Monday, March 21
Server is Flying
html data ======================> <body>

<h1></h1>
<ul>

    <li>Welcome to Fedex Staffing Beta!</li>

    <li>Geoffrey Singfred</li>

    <li>Elizabeth Holmes</li>

    <li>Diana Ross</li>

    <li>Frank</li>
  </ul>

</body>

[Error: 31772:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:
] {
  library: 'SSL routines',
  function: 'ssl3_get_record',
  reason: 'wrong version number',
  code: 'ESOCKET',
  command: 'CONN'
const express = require("express");
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
const date = require(__dirname + "/date.js");
const nodemailer = require("nodemailer");



// MONGO CONNECTION //
// This is the connection to the database. 27017 is the port mongo chooses by default

mongoose.connect("mongodb+srv://user-admin:[email protected]/cluster0?retryWrites=true&w=majority")

console.log("DB CONNECTION SUCCESSFUL")


// EE TABLE //
// This is the employee default schema. Just a name.
const itemsSchema = new mongoose.Schema ({
  item: String,
});

const listSchema = new mongoose.Schema({
  name: String,
  items: [itemsSchema]
});



// This initializes a new schema or what Mongo calls a collection. Each collection
// is essentially the equivalent of a table in SQL

const Item = mongoose.model("Item", itemsSchema);
const List = mongoose.model("List", listSchema);



// Write now the app starts with items by default. These are them. They can be deleted
// easily by checking the box in the app. I'm sure there is a better way to do this.

const item1 = new Item({
  item: "Welcome to Fedex Staffing!",
});


// Just a default list I use to call when a new page is created.

const defaultItems = [item1];


////// BEGIN APP //////

// Intitalize date
const day = date.getDate();

// Initialize express
const app = express();


// Initialize ejs
app.set("view engine", "ejs");
app.use(express.static("public"));


// Intialize body parser. 
app.use(bodyParser.urlencoded({
  extended: true
}));


// MAIN PAGE //


// A GET call to retrieve all current items in the database, if there are less
// than zero then it adds back the default items listed below
app.get("/", function(req, res) {

  Item.find({}, function(err, foundItems){ 

    if (foundItems.length === 0){
      Item.insertMany(defaultItems, function(err){
        if (err) {
          console.log(err);
        } else {
          console.log("Items successfully added.");
        }
      });
      res.redirect("/");
    } else {
      res.render("list", {listTitle: day,newListItems: foundItems});
    };
  });
});

// A POST call to add items to the list and the database
app.post("/", function(req, res) {


  const itemName = req.body.newItem;    
  const listName = req.body.list;      

  const item = new Item({
    item: itemName
  });

  if (listName === day){
    item.save();
    res.redirect("/");
  } else {
    List.findOne({name: listName}, function(err, foundList){  
      foundList.items.push(item);
      foundList.save();
      res.redirect("/" + listName);
    });
  };

});


// This delete route for when you check a checkbox, it then deletes the item. 

app.post("/delete", function(req, res){
  const checkedItemId = req.body.checkbox;
  const listName = req.body.listName;

  if (listName === day){
    Item.findByIdAndRemove(checkedItemId, function(err){ 
      if(!err) {
        console.log("Successfully deleted checked item")
        res.redirect("/");
      };
    });
  } else {
    List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
      if(!err){
        res.redirect("/" + listName);
      };
    });
  };

});

app.post("/send", function(req, res){
  const title = req.body.customName
  var transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 666,
      secure: true, // use SSL
      auth: {
          user: "***********@hellmail.com",
          pass: "*********"
      }
  });


  Item.find({}, function(err, foundItems){

  const data = ejs.renderFile(__dirname + "/views/emailtemp.ejs", {newListItems: foundItems, listTitle: title}, function (err, data) {
  if (err) {
      console.log(err);
  } else {
      var mainOptions = {
          from: '"Jesus"*************@gmail.com',
          to: "*********@gmail.com",
          subject: 'Hello, world',
          html: data
      };
      console.log("html data ======================>", mainOptions.html);
      transporter.sendMail(mainOptions, function (err, info) {
          if (err) {
              console.log(err);
          } else {
              console.log('Message sent: ' + info.response);
          }
      });
  }

  });
 });
});


console.log(day)


app.listen(process.env.PORT || 3000, function() {
  console.log("Server is Flying");
});
```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情独悲 2025-01-23 07:45:06

所以我第一次回答了我自己的问题。在我的代码中,当我初始化传输程序时,我将安全握手连接设置为“true”。我做了一些阅读,发现那里发生的事情与握手不匹配。在没有详细说明的情况下,我将其更改为“假”,而不是“真”,并且该应用程序第一次完美运行。

So I answered my own question for the first time. In my code, when I initialize the transporter, I have the handshake connection on secure set to 'true'. I did some reading and found that there is something going on there not matching the handshake. Without going into a ton of detail, I changed it to 'false', instead of 'true' and for the first time, the app works perfectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文