邮件不是由nodemailer发送的

时间:2019-05-20 12:32:04

标签: node.js nodemailer

我正在尝试使用nodemailer发送邮件,但是代码未发送邮件也未显示任何错误。通过用户输入,从主题添加到ejs表单中的邮件,并使用nodemailer添加邮件,我想将邮件发送到Gmail帐户,但未发送。请任何帮助

mail.ejs

<div class="card">
           <div class="card-header">
            <p>
                <b>Send mail</b>
            </p>
        </div>
            <br/>
                <form action="/send-email" method="post">
                    <div class="col-md-12" style="overflow-x:auto;">

                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="To" name="to" value="">
                            </div>

                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="From" name="from" value="">
                            </div>

                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Subject" name="message" value="">
                            </div>

                            <div class="form-group">
                                    <textarea class="form-control" id="" rows="4"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">Send</button>

                     </div>
                </form>
            <br/>
            <br/>

        </div>

Controller.js

router.get('/donation/mail', async (req,res) => {

  res.render('mail');

});
var transport = nodemailer.createTransport(smtpTransport({
  service: "gmail",
    auth: {
        // should be replaced with real sender's account
        user: 'xxxxx@gmail.com',
        pass: 'mygmailpassword'
    }
  }));

router.post('/send-email', function (req, res) {

  var mailOptions = {
      // should be replaced with real recipient's account
      to: req.body.to,
      from:'xxxxx@gmail.com',
      subject: req.body.subject,
      body: req.body.message
  };
  transport.sendMail(mailOptions, function(error, info) {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: ' + info.response);
});

res.redirect("/donation");
});

运行后获取消息 enter image description here

我的邮件表格 [在此处输入图片描述] [2]

1 个答案:

答案 0 :(得分:0)

使用gmail发送电子邮件之前,您必须允许不安全的应用访问gmail。这可以在您的gmail设置中完成:

https://myaccount.google.com/lesssecureapps?pli=1

我还可以推荐以下文章,以逐步说明如何使用gmail设置nodemailer: https://codeburst.io/sending-an-email-using-nodemailer-gmail-7cfa0712a799