首页 > 解决方案 > 如何在 Web 主机服务器中运行节点邮件程序

问题描述

我创建了一个页面,用于使用节点邮件程序将表单数据发送到 gmail 帐户。

要将页面表单数据发送到 gmail,我必须首先运行node server.js我配置节点邮件程序的服务器。它在本地运行良好,但在生产现场却没有。

运行 server.js 后很清楚,只有这样才有效。

但是我如何node server.js从网络托管服务器启动它以使其在生产站点中工作。

是否有任何不同的生产配置,例如在本地启动服务器,如下所述,

服务器.js

const nodemailer = require("nodemailer");
const xoauth2 = require("xoauth2");
const cors = require('cors');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// app.use(function (req, res, next) {
//   res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
//   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
//   res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Accept, Authorization');
//   res.setHeader('Access-Control-Allow-Credentials', true);
//   next();
// });

app.use(cors({ origin: "*" }));

app.use(bodyParser.json());
// app.use(bodyParser.json({limit: "50mb"}));
// app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

app.post('/sendFormData', (req, res) => {
  console.log(req.body, 'data of form');
  var transporter = nodemailer.createTransport({
    service: 'gmail',
    host: 'smtp.gmail.com',
    secure: 'true',
    port: '465',
    auth: {
      user: 'test@gmail.com', // must be Gmail
      pass: 'pass'
    }
  });

  var mailOptions = {
    from: `${req.body.email}`,
    to: 'test@gmail.com', // must be Gmail
    cc: `${req.body.name}`,
    subject: 'New Order',
    html: `
            <table style="width: 100%; border: 1px solid #6c0078">
              <thead>
                <tr style="background-color: #6c0078; color: #fff;">
                  <th style="padding: 10px 0">Name</th>                 
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style="text-align: center; border-right: 1px solid #6c0078;">${req.body.name}</td>                 

                </tr>
              </tbody>
            </table>
          `
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
      res.status(200).json({
        message: 'successfuly sent!'
      })
    }
  });

});

app.listen(3000, () => {
  console.log("server run!!!");
});

生产现场出错

在此处输入图像描述

标签: angularnodemailer

解决方案


确保您的端点看起来像http://serverIp:3000/sendFormData. 您还可以添加错误响应。

 transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      res.status(500).json({
       error
       });
    } else {
      console.log('Email sent: ' + info.response);
      res.status(200).json({
        message: 'successfuly sent!'
      })
    }
  });

推荐阅读