TypeError: nodemailer.createTransport is not a function

TypeError: nodemailer.createTransport is not a function

我正在尝试在我的 nodejs 应用程序中实现 nodemailer 来发送电子邮件。

这是我的代码

var express = require('express');
var nodemailer = require('node-mailer');

var app = express();
app.post('/contact/send', function(req, res) {
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'myEmailIdHere',
        pass: 'myPassword'
    }
});

var mailOptions = {
    from: 'myName <myEmailIdHere>',
    to: 'myOtherEmailIdHere',
    subject: 'Website Submission',
    text: 'You have a submission with the following details... Name: ' + req.body.name + ' Email: ' + req.body.email + ' Message: ' + req.body.message,
    html: '<p>You have a submission with the following details...</p><ul><li>Name: ' + req.body.name + '</li><li>Email: ' + req.body.email + '</li><li>Message: ' + req.body.message + '</li></ul>'
};
transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        console.log(error);
        res.redirect('/');
    } else {
        console.log('Message Sent: ' + info.response);
        res.redirect('/');
    }
})

提交表单后,出现错误

"TypeError: nodemailer.createTransport is not a function"

谁能帮我弄清楚如何使代码与 nodemailer 一起工作?

nodemailernode-mailer 是两个不同的模块。你应该使用正确的。

var nodemailer = require('nodemailer');

此外,请确保使用 npm i

安装了 nodemailer

看来你已经完成了

npm install node-mailer --save

这是哪个图书馆:https://www.npmjs.com/package/node-mailer

当您尝试按照此库的说明操作时:https://www.npmjs.com/package/nodemailer

要使您的代码正常工作,请执行

npm install nodemailer --save

然后要求模块为

var nodemailer = require('nodemailer')

不要在 node-mailer 之间加上连字符,它是一个不同的模块。

使用这个 var nodemailer = require('nodemailer');