条带化付款成功后,Nodemailer不发送电子邮件

时间:2019-08-06 22:26:08

标签: javascript node.js express handlebars.js nodemailer

通过条纹购买后,我正尝试向自己发送电子邮件。我目前有个人和企业电子邮件,我正在为此使用。我是node.js的新手,我对为什么它不起作用感到困惑。

对我来说有意义的是将此代码添加为.then回调的参数。在本地进行测试时,将显示成功页面,但是不会发送电子邮件,并且底部的两个console.log不会输出到控制台。以下是我的app.js

const express = require('express');
const stripe = require('stripe')('mystripekey');
const bodyParser = require('body-parser');
const exphps = require('express-handlebars');
const nodemailer = require('nodemailer')

var app = express();

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

app.engine('handlebars', exphps({defaultLayout: 'main'}));
app.set('view engine', 'handlebars')

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(express.static(`${__dirname}/public`));

app.get('/', (req, res) => {
    res.render('index');
});

app.post('/charge', (req, res) => {
    const amount = 25000;

    stripe.customers.create({
        email: req.body.stripeEmail,
        source: req.body.stripeToken
    })
    .then(customer => stripe.charges.create({
        amount,
        description: 'Advertisement',
        currency: 'usd',
        customer: customer.id
    }))
    .then(charge => {

        // This is where I'm getting confused
        res.render('success')

        var mailOptions = {
            from: req.body.stripeEmail,
            to: 'mybizemail@gmail.com',
            subject: 'A purchase was made',
            text: req.body.stripeEmail + ' made a purchase!'
          };

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

});

我希望记录错误消息或发送电子邮件记录,但是没有发生。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为节点邮件程序代码永远不会被调用。尝试将res.render放在transporter.sendMail的回调中。

像这样:

.then(charge => {
    console.log("charge>", charge);
    var mailOptions = {
        from: req.body.stripeEmail,
        to: 'mybizemail@gmail.com',
        subject: 'A purchase was made',
        text: req.body.stripeEmail + ' made a purchase!'
    };
    console.log("mailOptions>", mailOptions);  
    transporter.sendMail(mailOptions, function(error, info){
        console.log("error1>", error);
        console.log("info>", info);
        if (error) {
          console.log(error);
          res.render('error')
        } else {
          console.log('Email sent: ' + info.response);
          res.render('success')
        }
    });
});