Home > Net >  Nodemailer cant find txt file
Nodemailer cant find txt file

Time:11-30

I've been looking for an answer on here for this but so far nothings worked. Basically I've got a txt file and I want to send it using Nodemailer, thats it. But I keep getting this error: Error: ENOENT: no such file or directory, open 'data.txt' The file exists and in the same directly as the .js file tasked with sending it so the paths correct. I've checked my .json file and all packages I should need are present. This all works locally so I'm seriously struggling to understand whats wrong.

Heres the code:

let nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
service: 'outlook',
auth:{
    user: 'myEmail',
    pass: process.env.MAIL_PASS
}
});

data.map(coin => {
    if(coin.symbol !== 'BNB'){
        top80.push(coin.symbol.toUpperCase());
        cleanedOrders[coin.symbol.toUpperCase()] = [];
        }
    })

        let mailoptions = {
            from: 'senderEmail',
            to: 'toEmail',
            subject: 'Report',
            text: 'Find this months report attached.',
            attachments: [
                {
                    filename: 'report.txt',
                    path: 'data.txt'
                }
            ]
        }
        function getCoinData(numberOfCoins) {
            //should be < -1
            if (numberOfCoins > -1) {
                //console.log('All coin orders captured');
                //email results
                transporter.sendMail(mailoptions, (err, info) => {
                       if(err){
                           console.log(err);
                           res.json(`error compiling report: ${err}`);
                       } else {
                        res.json(`Report sent.`);
                       }
                   });
              }
            }

CodePudding user response:

Since you provide a relative path, the nodemailer will build up a path relative to process.cwd . The process.cwd() is the programs working dir or think of the location of your main.js file, the folder you start the program in!.

Say you have following folder structure:

main.js
-email
--email.js
--data.txt

If you start the program using main.js the process.cwd() argument will always be the folder the main.js is in even if the file email.js is called.

Option 1

  • Move data.txt to the root folder (same folder as main.js is in.) and it will find it.

Option 2

  • Provide an absolute path to nodemailer, best todo with global __dirname

var { join } = requiure('path')
let mailoptions = {
  from: 'senderEmail',
  to: 'toEmail',
  subject: 'Report',
  text: 'Find this months report attached.',
  attachments: [
    {
      filename: 'report.txt',
      
      // __dirname is equal to the directory the file is located in!.
      path: join(__dirname, 'data.txt')
    }
  ]
}

  • Related