连接nodemailer形成

Connect nodemailer to form

我有一个 mail.js 文件,当 运行 独立给我发邮件时。我有一个表格。我想将邮件发送到填写表格的电子邮件 ID。我怎样才能做到这一点?我无法连接这两个。

在哪里以及如何添加 mail.send();?如果这两个代码在不同的文件中,如何添加可变电子邮件?

我的html也在index.html

谢谢!!

index.html

<form action="/sign_up" method="POST" id="myForm">

              <div>
                <p class="cuboid-text">Subscribe</p>
              </div>

              <div>

                <label for="submit" class="submit-icon">
                  <i class="fa fa-chevron-right"></i>
                </label>
                <input type="text" id="email" class="cuboid-text" placeholder="Your Email" autocomplete="off" name="email"/>

                <input type="submit" id="submit" name="submit" class="submit" formaction="/sign_up" formmethod="POST"/>
              </div>

              <div>
                <p class="cuboid-text loader">Just a moment ...
                  <i class="fa fa-spinner fa-pulse"></i>
                </p>
              </div>
              <div>

                <span class="reset-icon"><i class="fa fa-refresh"></i></span>
                <p class="cuboid-text">Thankyou, we'll be in touch</p>
              </div>
            </form>

 <script>
    $("#email").focus(function () {
      $("#cuboid form").addClass("ready");
  
    })
    //remove '.ready' when user blus away but only if there is no content
    $("#email").blur(function () {
      if ($(this).val() == "")
        $("#cuboid form").removeClass("ready");
    
    })

    //If the user is typing something make the arrow green/.active
    $("#email").keyup(function () {
      //this adds .active class only if the input has some text
      $(".submit-icon").toggleClass("active", $(this).val().length > 0);
  
    })

    $("#cuboid #myForm").submit(function () {
      const re = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
  const email=document.getElementById("email").value;
  const re1='abcd';
  console.log(email);
      
      //prevent default form submisson
      if(re.test(String(email).toLowerCase())){
        console.log("true");
        document.getElementById("demo1").style.visibility="hidden";
        $(this).removeClass("ready").addClass("loading");
        setTimeout(complete, 3000);
      return true;}
      else{
        document.getElementById("demo1").style.visibility="visible";
        // setTimeout(complete, 1000);
      return false;
      }
    })
    

    function complete() {
      $("#cuboid form").removeClass("loading").addClass("complete");
    }
    //reset/refresh functionality
    $(".reset-icon").click(function () {
      $("#cuboid form").removeClass("complete");
  
    })




  </script>

index.js

var express = require("express")
var bodyParser = require("body-parser")
var mongoose = require("mongoose")


const app = express()

app.use(bodyParser.json())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
    extended: true
}))

mongoose.connect('mongodb://localhost:27017/mydb123', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

var db = mongoose.connection;

db.on('error', () => console.log("Error in Connecting to Database"));
db.once('open', () => console.log("Connected to Database"));





app.post("/sign_up", (req, res) => {
    // var name = req.body.name;
    var email = req.body.email;

    // var phno = req.body.phno;
    // var password = req.body.password;
    // var initrefnum = req.body.demo;
    // var newrefnum = req.body.newdemo;

    console.log("step1");

    var data = {
        // "name": name,
        "email": email
        // "initrefnum": initrefnum,
        // "newrefnum": newrefnum
    }


    db.collection('users').insertOne(data, (err, collection) => {
        if (err) {
            throw err;
        }
        console.log("Record Inserted Successfully");
    });

    // return res.redirect('index.html')


})



app.get("/", (req, res) => {
    res.set({
        "Allow-access-Allow-Origin": '*'
    })
    return res.redirect('index1.html');
}).listen(3000);


console.log("Listening on PORT 3000");

mail.js


const nodemailer=require('nodemailer')

let mailTransporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'mail@gmail.com',
        pass: '*********'
    }
});

let mailDetails = {
    from: 'xyz@gmail.com',
    to: 'abc@gmail.com',
    subject: 'Test mail',
    text: 'Node.js testing mail for GeeksforGeeks'
};

mailTransporter.sendMail(mailDetails, function(err, data) {
    if(err) {
        console.log('Error Occurs');
    } else {
        console.log('Email sent successfully');
    }
});

就是这个<input type="submit" id="submit" /> 要么 <button type="submit">Submit</button> 可以

app.use(express.static('public')) // 如果您认为还需要做些什么来连接,这就足够了。

Mail.js

const nodemailer = require('nodemailer');

let mailTransporter = nodemailer.createTransport({
     service: 'gmail',
     host: 'smtp.gmail.com',
     auth: {
       user: 'dee@gmail.com', //this should be same as 'from' address
       pass: 'workingpassword'
      } 
   });

module.exports = mailTransporter;

App.js

const mailTransporter = require('./mail);

对于您的表单操作,在您的 /sign_up post 方法中执行以下操作

app.post('/sign_up', (req, res)=>{
  
  mailTransporter.sendMail({
    from: 'dee@gmail.com',  //this should be same as above auth.user
    to: `${req.body.email}`,
    subject: 'Test',
    text: 'hello',
    html: `Hello ${req.body.name} thank you for contacting. We will get in touch`
  }).then(res=>{
      console.log("success........", res)
      resp.send(`email sent to ${req.body.name}` successfully);
  }).catch(e=>{
      console.log("failed........", e)
  });
});

避免问题的方法,

转到 https://myaccount.google.com/lesssecureapps 并为安全性较低的应用程序启用。

转到 https://accounts.google.com/DisplayUnlockCaptcha 并启用。