Sending email via Node.js using nodemailer is not working

后端 未结 9 1854
悲&欢浪女
悲&欢浪女 2020-11-29 20:15

I\'ve set up a basic NodeJS server (using the nodemailer module) locally (http://localhost:8080) just so that I can test whether the server can actually send ou

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 21:09

    i just set my domain to: smtp.gmail.com and it works. I am using a VPS Vultr.

    the code:

    const nodemailer = require('nodemailer');
    const ejs = require('ejs');
    const fs = require('fs');
    
    let transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        auth: {
            user: 'xxx@gmail.com',
            pass: 'xxx'
        }
    });
    
    let mailOptions = {
        from: '"xxx" ',
        to: 'yyy@gmail.com',
        subject: 'Teste Templete ✔',
        html: ejs.render( fs.readFileSync('e-mail.ejs', 'utf-8') , {mensagem: 'olá, funciona'})
    };
    
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s', info.messageId, info.response);
    });
    

    my ejs template (e-mail.ejs):

    
        
            Esse é um templete teste
            

    gerando com o EJS - <%=mensagem%>

    Make sure:

    • install ejs: npm install ejs --save
    • install nodemailer: npm install nodemailer --save
    • ping to smtp.gmail.com works: ping smtp.gmail.com
    • change xxx@gmail.com to your gmail email
    • change yyy@gmail.com to the email that you want to send a email
    • Enable less secure apps
    • Disable Captcha temporarily

    have a nice day ;)

提交回复
热议问题