node.jsexpressenvironment-variablesnodemailernodemon

ReferenceError: transporter is not defined


i am new in react js am getting an error when i am trying to run my node js server the error is mentioned in my title box please try to fix it as soon as possible.

index.js

this is my index.js file where i wrote my all backend code

let express = require('express');
let app = express();
const path = require('path');
let nodemailer = require('nodemailer');

// Static folder

    app.use('/public', express.static(path.join(__dirname, 'public')));
    
    nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: "harsalpatil512@gmail.com",
        pass: "*********" 
      }
    });
    
    // verifying the connection configuration
    transporter.verify(function(error, success) {
      if (error) {
        console.log(error);
      } else {
        console.log("Server is ready to take our messages!");
      }
    });
    
    
    router.post('/access', (req, res, next) => {
      var name = req.body.name
      var email = req.body.email
      var message = req.body.message
      var content = ` name: ${name} \n email: ${email} \n message: ${message} `
    
      var mail = {
        from: "harsalpatil512@gmail.com", 
        to: "ashishnirvikar5670@gmail.com", 
        message: "Welcome to Gmail",
        text: "Thanks for contacting us"
      }
    
      transporter.sendMail(mail, (err, data) => {
        if (err) {
          res.json({
            status: 'fail'
          })
        } else {
          res.json({
           status: 'success'
          })
        }
      })
    })
    
    
    const PORT = process.env.PORT || 8080
    app.listen(PORT, () => console.info(`server has started on ${PORT}`))

Solution

  • you need to make a little change:

     // need to declare transporter first 
    const transporter = nodemailer.createTransport({
          service: 'gmail',
          auth: {
            user: "harsalpatil512@gmail.com",
            pass: "*********" 
          }
        });