Send email with Nodemailer on Locallhost (ReferenceError: require is not defined)

0

I want to send the data of this form with Nodemailer. But when I click the button enviar in the browser (locallhost) in the console I get the following error: ReferenceError: require is not defined . My version of node is v7.9.0 .

I must clarify that when I run app.js from the terminal (without the function) function enviar(){} if it sends the mail.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Demo4</title>
    </head>
    <body>
        <h1>Formulario</h1>
        <select>
            <option>Vida</option>
            <option>Hogar</option>
            <option>Auto</option>
        </select>
        <br>
        <input type="email" value="email">
        <br><br>
        <input type="button" value="enviar" onclick="enviar()">
        
        <script src="app.js"></script>
    </body>
</html>

app.js

function enviar(){

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

    let mailOptions = {
        from: '"****" <****@gmail.com>',
        to: '****@***.com',
        subject: 'Lorem ipsum',
        text: 'Lorem ipsum',
        html: '<b>Hello world ?</b>'
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s', info.messageId, info.response);
    });
    
};

app.js without the function function enviar(){} Tested from the terminal if you send the email.

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

    let mailOptions = {
        from: '"****" <****@gmail.com>',
        to: '****@***.com',
        subject: 'Lorem ipsum',
        text: 'Lorem ipsum',
        html: '<b>Hello world ?</b>'
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s', info.messageId, info.response);
    });
    
asked by Paco Zevallos 15.08.2017 в 20:41
source

1 answer

0

Place the require before declaring the function, otherwise it will try to solve "require" within the scope of the function instead of the scope of the application

var nodemailer = require('nodemailer');

function enviar(){...}
    
answered by 30.08.2017 в 00:26