与Gmail一起使用Nodemailer

时间:2019-05-17 06:49:22

标签: javascript node.js nodemailer

我一直在阅读各种论坛,并尝试了许多小时才能使Nodemailer应用程序正常工作,但它根本无法正常工作。我接受了能够使他们工作的人们的建议,但结果对我来说仍然是相同的。每当我尝试以创建的表单发送POST请求时,我都会收到以下错误消息。

更新:!!

我设法获得了链接到电子邮件的代码,但是现在我无法将数据输入到联系表单中以提交给电子邮件。我有点新,所以如果我听起来没经验,那就是。感谢您的耐心配合。这是当前代码:

app.post('/contact',urlencodedParser,(req,res)=>{
    const output= `
    <p>You have a new contact request</p>
    <h3>Contact Details</h3>
    <ul>
         <li> Name:${req.body.name}</li>
         <li> Email:${req.body.email}</li>
        <li> Message:${req.body.message}</li>

    </ul>

    `;

    async function main(){



    let transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,

        auth: {
            user:'ME@EMAIL.COM',
            pass: process.env.PASSWORD

        },

    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: req.body.email, // sender address
      to: "me@email.com", // list of receivers
      subject: "Hello ✔", // Subject line
       html: `${req.body.message}` // html body
    });

    console.log("Message sent: %s", info.messageId);

    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

  }

  main().catch(console.error);


res.render('contact')

})

1 个答案:

答案 0 :(得分:1)

这只是一个忘记密码的控制器,它会向用户发送密码。 emailConfig.js

var email = "xxxx@gmail.com";
const password = "xxxxxx";
const service = "gmail";

module.exports = {
  service: service,
  email: email,
  password: password
}

Controller.js

var transporter = nodemailer.createTransport({
    service : nodeMailerConfig.service,
    auth :{
        user : nodeMailerConfig.email,
        pass : nodeMailerConfig.password
    }
});
    const mailOptions = {
                          from: nodeMailerConfig.email,
                          to: req.body.email,
                          subject: "Forgot Password",
                          html: `<p>Hi ${req.body.email}</p> <br/>
                                  <pre>Your password is ${randomPassword}</pre><br/>
                                  <pre>Cheers, OpenBox Team</pre>`
                          }
                          transporter.sendMail(mailOptions,(mailerr,info)=> {
                              if(mailerr){
                                res.status(400).json("Unable to send email");
                              }else{
                                res.status(201).json(info);
                              }
                          })