Node.js 和 Express.js 和 AngularJs 的电子邮件和 nodemiailer 不发送邮件

Email with Node.js and Express.js and AngularJs and nodemiailer not sending mail

我查看了各种教程并进行了很多关于使用 Node.js 和 Express.js 通过 HTML 和 AngularJs 页面发送基本电子邮件的搜索,但是根本无法让我的实施工作。我知道我错过了一些愚蠢的东西。

我选择使用 nodemailer 作为 Node.js 包,并在我的 Express.js API 中使用它来发送实际的邮件。

我的视图到API的路径如下:视图(窗体)>>控制器>>邮件工厂>>API

我得到了每个步骤的结果(数据的控制台日志),但是电子邮件发送失败。

在 Chrome 开发工具中,我在 Headers 中得到了 200 OK 的状态代码,但它实际上失败了。在“响应”或“预览”下查看时,我收到以下消息:

{error: "connect ETIMEDOUT 64.233.184.109:465"}
error:"connect ETIMEDOUT 64.233.184.109:465"

在 Bash 控制台(我在 运行 我的服务器上)我可以看到 API 端点被命中,因为我得到这个 console.log 输出:

THIS IS THE API HIT:Email to: corne.leroux@outlook.comSubject: This is my subjectMessage: This is my message

我一直在使用的一些参考资料:

http://javascript.tutorialhorizon.com/2015/07/02/send-email-node-js-express/

https://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer

我是 Express.js 的绝对新手,对 Node.js 的了解有限。

这是我的基本实现:

HTML 查看:

<div class="container">
    <form name="createEmailForm" method="post" action="" class="form-horizontal" role="form">
        <div class="form-group">
            <label for="emailAddress" class="col-lg-3 col-md-3 col-xs-12 control-label">From Email Address</label>
            <div class="col-lg-9 col-md-9 col-xs-12">
                <input ng-model="formData.emailAddress" type="text" class="form-control" id="emailAddress" name="emailAddress" placeholder="Email Address" required>
            </div>
        </div>
        <div class="form-group">
            <label for="clientName" class="col-lg-3 col-md-3 col-xs-12 control-label">Name</label>
            <div class="col-lg-9 col-md-9 col-xs-12">
                <input ng-model="formData.clientName" type="text" class="form-control" id="clientName" name="clientName" placeholder="Name" required>
            </div>
        </div>
        <div class="form-group">
            <label for="clientMessage" class="col-lg-3 col-md-3 col-xs-12 control-label">Message</label>
            <div class="col-lg-9 col-md-9 col-xs-12">
                <input ng-model="formData.clientMessage" type="text" class="form-control" id="clientMessage" name="clientMessage" placeholder="Message" required>
            </div>
        </div>
    </form>
    <button class="btn btn-primary" ng-click="submit(formData)">Send</button>
</div>

AngularJs 控制器:

$scope.submit = function () {
    var formData = $scope.formData;
    console.log(JSON.stringify($scope.formData));
    sendMail(formData);
};

function sendMail(formData) {
    console.log('createEmail: ', formData);
    return EmailFactory.sendMail(formData)
        .then(function (data, status, headers, config) {
            console.log("Email Sent");
        });
}

AnularJs 工厂:

function sendMail() { 
    return $http.post('/api/send')
    .then(Success)
    .catch(Failure);

    function Success(responce) {
        console.log(responce.data);
        return responce.data;
    }

    function Failure(error) {
        console.log('A problem occurred while sending an email.' + JSON.stringify(error));
    }
}

Express.js API

var express = require('express');
var nodemailer = require("nodemailer");
var router = express.Router();
var mongoose = require('mongoose');
var customers = require('../schemas/customers.js');
var suppliers = require('../schemas/suppliers.js');
var products = require('../schemas/products.js');

var smtpTransport = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
        user: "cjleroux8@gmail.com",
        pass: "*********"
    }
});

router.post('/send', function (req, res, next) {
    var mailOptions = {
        to: req.body.emailAddress,
        subject: req.body.clientName,
        text: req.body.clientMessage
    }

    console.log('THIS IS THE API HIT:' + 'Email to: ' + mailOptions.to + 'Subject: ' + mailOptions.subject + 'Message: ' + mailOptions.text);

    smtpTransport.sendMail(mailOptions, function (error, response) {
        if (error) {
            console.log(error);
            res.json({error: "API Error"});
        } else {
            console.log("Message sent: " + response.message);
            res.json({ response: "sent" });
        }
    });
});

这是我的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');

mongoose.Promise = global.Promise;

mongoose.connect(process.env.MONGO_CON || 'mongodb://127.0.0.1:27021/impi');

var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'html');

app.use(express.static(__dirname));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
app.use('/api', api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

这是我的index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile('index.html');
});

module.exports = router;

我已经实现了一个使用nodejs和express发送邮件的基本应用。我使用了 nodemailer 模块,但我没有在我的应用程序中添加 mongodb。如果您习惯,请检查下面我的代码。

Index.html

<html>
   <head>
      <title>Node.JS Email application</title>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script>// <![CDATA[
         $(document).ready(function() {
            var from, to, subject, text;
            $("#send_email").click(function() {
                to = $("#to").val();
                subject = $("#subject").val();
                text = $("#content").val();
                $("#message").text("Sending E-mail...Please wait");
                $.get("http://192.168.2.47:3000/send", {
                    to: to,
                    subject: subject,
                    text: text
                }, function(data) {
                    if (data == "sent") {
                        $("#message").empty().html("Email is been sent at " + to + " Please check inbox!");
                    }

                });
            });
        });
      </script>
   </head>
   <body>
      <div id="container">
         <h1>Mailer In Node.JS</h1>
         <br/>
         <input id="to" type="text" placeholder="Enter E-mail ID where you want to send" /><br/>
         <input id="subject" type="text" placeholder="Write Subject" /><br/>
         <textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
         <br/>
         <button id="send_email">Send Email</button>
         <span id="message"></span>
      </div>
   </body>
</html>

server.js

var express = require('express');
var nodemailer = require("nodemailer");
var app = express();
var smtpTransport = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
        user: "******",
        pass: "***"
    }
});

app.get('/', function(req, res) {
    res.sendfile('index.html');
});

app.get('/send', function(req, res) {
    //code to send e-mail.
    //Will be shown soon.
    var mailOptions = {
        to: req.query.to,
        subject: req.query.subject,
        text: req.query.text
    }
    console.log(mailOptions);
    smtpTransport.sendMail(mailOptions, function(error, response) {
        if (error) {
            console.log(error);
            res.end("error");
        } else {
            console.log("Message sent: " + response.message);
            res.end("sent");
        }
    });

});

app.listen(3000, function() {
    console.log("Express Started on Port 3000");
});

userpassserver.js 文件中使用有效的邮件 ID 及其密码。

您的工厂函数 sendMail 应该有 formData 参数,然后在 post 请求中发送该数据。 工厂应该是这样的:

function sendMail(formData) { 
    return $http.post('/api/send', formData)
    .then(Success)
    .catch(Failure);

    function Success(responce) {
        console.log(responce.data);
        return responce.data;
    }

    function Failure(error) {
        console.log('A problem occurred while sending an email.' + JSON.stringify(error));
    }
}

为了你的 API

要发送电子邮件,您应该为 nodemailer 设置 from 电子邮件,这样您就可以设置

var smtpTransport = nodemailer.createTransport({
    service: "Gmail",
    host: "smtp.gmail.com",
    auth: {
        user: "cjleroux8@gmail.com",
        pass: "*********"
    }
},
{
   from: 'example@gmail.com',
});

router.post('/api/send', function (req, res, next) {
    var mailOptions = {
        to: req.body.emailAddress,
        subject: req.body.clientName,
        text: req.body.clientMessage
    };

    console.log('THIS IS THE API HIT:' + 'Email to: ' + mailOptions.to + 'Subject: ' + mailOptions.subject + 'Message: ' + mailOptions.text);

    smtpTransport.sendMail(mailOptions, function (error, response) {
        if (error) {
            console.log(error);
            res.json({error: "API Error"});
        } else {
            console.log("Message sent: " + response.message);
            res.json({ response: "sent" });
        }
    });
});

你可以在mailOptions

中设置from
var mailOptions = {
        from: 'example@gmail.com',
        to: req.body.emailAddress,
        subject: req.body.clientName,
        text: req.body.clientMessage
    }