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

Posted

技术标签:

【中文标题】使用 Node 和 Express 发送邮件时出错【英文标题】:Error while sending mail with Node and Express 【发布时间】:2021-01-09 08:58:12 【问题描述】:

我正在尝试使用 nodemailer 在提交 html 表单时发送邮件。但是当我按下提交按钮时,它会显示这个错误......

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)

我只收到一封没有任何主题和正文的空白邮件。 我尝试更改函数名称,以免它与内置函数冲突。我还尝试将其数据类型从“const”更改为“function”。但这无济于事。我该如何解决这个问题?

index.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

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));

发送邮件.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();

【问题讨论】:

【参考方案1】:

错误消息说sendMail 不是函数。因此,您需要查看并确定它是什么

你在这里给它赋值:

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

因此查看该文件并查看它是否导出:

module.exports = sendMail();

要为export 设置值,您需要调用 sendMail 并分配其返回值。

其中没有return 语句,所以它返回undefined


如果要导出sendMail 函数,请导出函数本身。不要附加() 来调用它并获取它的返回值。

【讨论】:

【参考方案2】:

您正在导出 sendMail 的返回值而不是函数本身:

module.exports = sendMail();

改成:

module.exports = sendMail;

【讨论】:

【参考方案3】:

在 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()

【讨论】:

以上是关于使用 Node 和 Express 发送邮件时出错的主要内容,如果未能解决你的问题,请参考以下文章

从服务器从 nodemailer 发送电子邮件时出错

使用 bcryptjs 将散列密码保存到数据库时出错

node.js使用Nodemailer发送邮件

尝试通过 express node.js 提供 ejs 文件时出错

如何配置Node email-template使用SendGrid作为传输方式

尝试使用 Flask 和 Gmail 发送电子邮件时出错