Nodemailer 不发送电子邮件,也不 return 错误消息

Nodemailer doesn't send emails, and doesn't return an error message

我想知道为什么 nodemailer 不发送电子邮件,但它没有返回任何错误,所以我不知道该怎么做。这是我的代码(几乎是从 nodemailer 文档中复制的):

var cors = require('cors');
var corsOptions = {
    origin: 'http://davidmichael.me',
    allowedHeaders: 'accept, content-type',
    methods: 'GET, POST'
};

var nodemailer = require('nodemailer');

module.exports = function(app){
    app.options('/email', cors(corsOptions));
    app.post('/email', cors(corsOptions), function(req, res){
        var transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: 'my-email',
                pass: 'my-password'
            }
        });

        var mailOptions = {
            from: 'David Michael <my-email>',
            to: 'recipient-email',
            subject: 'Just verifying your email address ✔',
            text: 'Hello to myself!',
            html: '<p><b>Hello</b> to myself</p>'
        };
        var emailMessage = "";

        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                emailMessage = "there was an error :-(, and it was this: " + error.message;
            }else{
                emailMessage = "Message sent: " + info.response;
            }
        });
        //transporter.close();
        return res.json({
            message: "success",
            email: emailMessage
        });
    });
};

每次尝试都成功 returns 最后的 JSON 对象如下:

{"message":"success","email":""}

也许我应该注意,我正在使用 CORS,因为我想获取用户的电子邮件地址。我的客户端应用程序发送一个 HTTP POST 请求,其中包含一个 JSON 对象,其中包含他们的电子邮件地址——但是,当前代码还没有对此做任何事情。我想先让基本机制发挥作用。

我正在使用 Openshift。这会有所作为吗?

此外,我尝试过使用非 Gmail 电子邮件地址,但同样的事情发生了。

关于我哪里出错的任何想法?

看起来您在异步方法 returns 之前返回 JSON 响应。尝试将响应放入回调中:

transporter.sendMail(mailOptions, function(error, info){
        if(error){
            emailMessage = "there was an error :-(, and it was this: " + error.message;
        }else{
            emailMessage = "Message sent: " + info.response;
        }
        return res.json({
          message: "success",
          email: emailMessage
        });
    });
    //transporter.close();

虽然您可能不想在实践中使用它。等待电子邮件发送可能很耗时,我怀疑您会看到很多超时。不过,这应该能让您朝着正确的方向前进!

这还假设您的电子邮件地址已全部设置好,并且您也输入了真实的收件人。我知道我在使用 Gmail 时遇到了问题,因为它们非常擅长检测机器人 :)