简体   繁体   English

使用 Node 和 Express 发送邮件时出错

[英]Error while sending mail with Node and Express

I'm trying to send mail on submission of an HTML form using nodemailer.我正在尝试使用 nodemailer 在提交 HTML 表单时发送邮件。 But wheneve I'm pressing submit button it is showing this error...但是当我按下提交按钮时,它会显示此错误...

TypeError: sendMail is not a function
    at C:\Users\user\Desktop\project\Internship designs\notchup\server.js:20:3
    at Layer.handle [as handle_request] (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\body-parser\lib\types\json.js:101:7)
    at Layer.handle [as handle_request] (C:\Users\user\Desktop\project\Internship designs\notchup\node_modules\express\lib\router\layer.js:95:5)

And I'm only getting a blank mail without any subject and body.我只收到一封没有任何主题和正文的空白邮件。 I've tried changing the function name so that it might not conflict with the built in function.我已尝试更改函数名称,以免与内置函数发生冲突。 I've also tried to change it's data type to 'function' from 'const'.我还尝试将其数据类型从“const”更改为“function”。 But it couldn't help.但它无能为力。 How can I solve this?我该如何解决这个问题?

index.html索引.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form class="">
      <input type="text" id="subject" placeholder="Subject"><br>
      <input type="email" id="email" placeholder="Email"><br>
      <textarea name="text" id="text" rows="10" cols="30"></textarea><br>
      <input type="submit" value="Submit">

    </form>

    <!-- JQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- CUSTOM script -->
    <script>
        $('form').on('submit', (e) => {
          e.preventDefault();

          const email = $('#email').val().trim();
          const subject = $('#subject').val().trim();
          const text = $('#text').val().trim();

          const data = {
            email,
            subject,
            text
          };

          $.post('/email',data, function() {
            console.log('Server received our data');
          });

        });
    </script>
  </body>
</html>

server.js服务器.js

const express = require('express');
const sendMail = require('./send-mail');
const app = express();
const path = require('path');

const PORT = 8080;

// Data Parsing
app.use(express.urlencoded({
  extended: false
}));
app.use(express.json());

app.post('/email', (req, res) => {
  // TODO
  // send email here
  const { subject, email, text } = req.body;
  console.log('Data: ', req.body);

  sendMail(email, subject, text, function(err, data) {
    if (err) {
      res.status(500).json({ message: 'Internal Error' });
    } else {
      res.json({ message: 'Email sent!!!' });
    }
  });
  res.json({ message: 'Message received!!!' })
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
});

app.listen(PORT, () => console.log('Server is starting on PORT, ', 8080));

send-mail.js发送邮件.js

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'saxena1975sanjeev@gmail.com',
    pass: 'my_password'
  }
});

const sendMail = (email, subject, text) => {
  const mailOptions = {
    from: email,
    to: 'saxena1975sanjeev@gmail.com',
    subject: subject,
    text: text
  };

  transporter.sendMail(mailOptions, function(error, info) {
    if(error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
}

module.exports = sendMail();

The error message says that sendMail is not a function.错误消息说sendMail不是函数。 So you need to look and determine what it is .因此,您需要查看并确定它什么。

You assign it a value here:您在此处为其分配一个值:

 const sendMail = require('./send-mail');

So look in that file and see that it exports:因此,查看该文件并查看它导出:

 module.exports = sendMail();

To set a value for export you are calling sendMail and assigning its return value.要设置export值,您需要调用sendMail并分配其返回值。

There's no return statement in it, so it returns undefined .其中没有return语句,因此它返回undefined


If you want to export the sendMail function, then export the function itself .如果要导出sendMail函数,则导出函数本身 Don't append () to call it and get its return value.不要追加()来调用它并获取它的返回值。

You are exporting the return value of sendMail instead of the function itself:您正在导出 sendMail 的返回值而不是函数本身:

module.exports = sendMail();

Change it to:将其更改为:

module.exports = sendMail;

In send-mail.js instead of executing the sendMail function just send the reference of the function.在 send-mail.js 中,不是执行 sendMail 函数,而是发送函数的引用。

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'saxena1975sanjeev@gmail.com',
    pass: 'my_password'
  }
});

const sendMail = (email, subject, text) => {
  const mailOptions = {
    from: email,
    to: 'saxena1975sanjeev@gmail.com',
    subject: subject,
    text: text
  };

  transporter.sendMail(mailOptions, function(error, info) {
    if(error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
}

module.exports = sendMail; // don't sendMail()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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