简体   繁体   中英

Getting nodeJS web server to send form data to my email

I am trying to get the data my nodeJS server is receiving from a form on the front end to send that data to my email. I have tried to use nodemailer and haven't succeeded much. Can someone tell me perhaps what I am doing wrong with the following code?

const express = require("express");
const app = express();
const nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");

const PORT = process.env.PORT || 4000;

app.use(express.static(__dirname + "/front-end"));

app.get("/", (req, resp) => {
  resp.sendFile(__dirname + "/front-end/index.html");
});

app.use(express.json());
app.use(express.urlencoded());

app.post("/formData", (req, resp) => {
  const data = req.body;

  var transport = nodemailer.createTransport(
    smtpTransport({
      service: "Gmail",
      auth: {
        user: "user@gmail.com",
        pass: "123456",
      },
    })
  );

  transport.sendMail(
    {
      //email options
      from: "Sender Name <email@gmail.com>",
      to: "Receiver Name <receiver@email.com>", // receiver
      subject: "Emailing with nodemailer", // subject
      html: data, // body (var data which we've declared)
    },
    function (error, response) {
      //callback
      if (error) {
        console.log(error);
      } else {
        console.log("Message sent:");
        resp.send("success!");
      }

      transport.close();
    }
  );
});

app.listen(PORT, () => {
  console.log(`server running on port ${PORT}`);
});

Your code, at a glance, looks fine to me. I think the problem is (since you're not stating you have set that up), that you want to send email with GMail. If you want to send email from your own app or web service via Gmail, you should set up a project in the Google Cloud Platform. Read more here .

Alternatively, you could use a service like Postmark , which you can configure to send emails via a domain that you own. There's a free trial. Mailgun is a similar service. (I'm not affiliated to either).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM