尝试联系server.js发送电子邮件时出现错误500

时间:2019-05-03 15:51:47

标签: node.js angular

我正在尝试部署一个有角度的7网站,该网站使用nodemailer发送接收电子邮件,但不断出现错误500内部服务器错误。

一堆的角度很好,但我似乎无法弄清楚如何在网络上运行节点服务器(我意识到这可能是一个愚蠢的问题,但请原谅我是新手)

这是我与我们联系的服务

  url: string = "/send";  //THIS MIGHT BE A PROBLEM

  constructor(private http: HttpClient) {}

  sendMessage(messageContent: any) {
    return this.http.post(this.url, JSON.stringify(messageContent), {
      headers: new HttpHeaders({ "Content-Type": "application/json" }),
      responseType: "text"
    });

这是我的server.js文件

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

const transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  provider: "gmail",
  port: 465,
  secure: true,
  auth: {
    user: "an email",
    pass: "a password"
  },
  tls: {
    rejectUnauthorized: false
  }
});

app.use(bodyParser.json());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.post("/send", function(req, res) {
  let senderName = req.body.name;
  let senderEmail = req.body.email;
  let messageSubject = req.body.subject;
  let messageText = req.body.message;
  let copyToSender = req.body.contactFormCopy;

  let mailOptions = {
    to: ["anemail"],
    from: senderName,
    subject: messageSubject,
    text: messageText,
    replyTo: senderEmail
  };

  if (senderName === "") {
    res.status(400);
    res.send({
      message: "Bad request"
    });
    return;
  }

  if (senderEmail === "") {
    res.status(400);
    res.send({
      message: "Bad request"
    });
    return;
  }

  if (messageSubject === "") {
    res.status(400);
    res.send({
      message: "Bad request"
    });
    return;
  }

  if (messageText === "") {
    res.status(400);
    res.send({
      message: "Bad request"
    });
    return;
  }

  if (copyToSender) {
    mailOptions.to.push(senderEmail);
  }

  transporter.sendMail(mailOptions, function(error, response) {
    if (error) {
      console.log(error);
      res.end("error");
    } else {
      console.log("Message sent: ", response);
      res.end("sent");
    }
  });
});

app.listen(port, function() {
  console.log("Express started on port: ", port);
});

0 个答案:

没有答案