NodeMailer работает неправильно при отправке пользовательских файлов - PullRequest
0 голосов
/ 21 декабря 2018

Я пытаюсь создать на своем веб-сайте функцию, которая позволит мне получать электронные письма с вложениями от пользователей.Письмо должно быть отправлено только на мой адрес электронной почты, и я указал это соответствующим образом (*** для конфиденциальности).

Проблема с версия 1 в том, что я не могу просмотреть содержимое вложения.Письмо отправляется мне правильно, и в нем говорится, что вложение есть, но когда я открываю файл, оно остается пустым (относится к .pdf, .doc, .docx и .txt)

проблема с версия 2 заключается в том, что всякий раз, когда я прикрепляю файл, я даже не получаю сообщение, UNLESS файл, который я прикрепляю, находится в той же папке, что и «NoteLink», котораяместо, где я запускаю свой сервер, также известный как npm start

Спасибо за ЛЮБУЮ помощь и счастливых праздников!

Примечание: единственное, что я изменяю в обеих версиях, это "filePath (версия 1) "vs" путь (версия 2) "

.

.

.

.

применимо. JS версия 1

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb')
var assert = require('assert')
var url = 'mongodb://localhost:27017/NoteLink'
var mongoUtil = require('../mongoUtil');
var db = mongoUtil.getDb();
var nodemailer = require('nodemailer');
//for the nodemailer
var fileextensions = ['.doc','.docx','.pdf', '.txt'];
var ext;

/* GET home page. */
router.get('/', ensureAuthenticated, function (req, res, next) {
  //Andre, these commands might be of use, with the file path issue w/nodemailer
  //console.log(__dirname); //returns the current working directory
  //console.log(process.pwd()); //returns the directory that Node is executed froma
  res.render('apply')
  //hello();
})

  //How to create your own functions 
  function hello() {
    console.log('hello')
  }


router.post('/', ensureAuthenticated, function (req, res, next) {
  var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    //auth is the sender
    auth: {
      user: '***',
      pass: '***'
    }
  })
  for(var i = 0; i < fileextensions.length; i++) {
    if(req.body.transcript.includes(fileextensions[i])) {
      ext = fileextensions[i];
    }
  }
  let mailOptions = {
    from: '***',
    to: '***',
    subject: 'Example',
    attachments: [{
      filename: 'Transcript' + ext,
      filePath: req.body.transcript //BUG: attaches file, but file is blank
    }],
    text: 'Class request: ' + req.body.ApplyForClass + "\n"
          + 'Response: ' + req.body.Question + "\n" 
          + 'Email: ' + req.body.Email + "\n"
  }

    //Create a function here that checks the validity of the email

    transporter.sendMail(mailOptions, function(error, info) {
      if (error) {
        return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);
      console.log('file path? %s', req.body.transcript)
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    })





      req.flash('success', 'Tutor status: pending');
      res.redirect('/home');

})

function ensureAuthenticated(req, res, next){
 if(req.isAuthenticated()){
  return next();
 }
 res.redirect('/users/login');
}
module.exports = router;

Сообщение командной строки Apply.JS версии 1

express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option app.js:40:9
app working on 3000
GET /apply?become=Become+a+Tutor 304 341.969 ms - -
GET /stylesheets/bootstrap.css 304 2020.632 ms - -
GET /stylesheets/style.css 304 2020.239 ms - -
GET /javascripts/bootstrap.js 304 3011.284 ms - -
POST /apply 302 46.032 ms - 54
GET /home 304 75.845 ms - -
GET /stylesheets/bootstrap.css 304 7.545 ms - -
GET /stylesheets/style.css 304 8.474 ms - -
GET /javascripts/bootstrap.js 304 10.867 ms - -
Message sent: <7a1989a2-3966-3bba-a418-5326dd948cb6@gmail.com>
file path? Psychology CAP paper.docx
Preview URL: false

apply.JS версия 2

/**
If the emailer still does not work, then one of us will have to do a COMPLETE rehaul
on the fiel structure so, that we can make it work.
*/

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb')
var assert = require('assert')
var url = 'mongodb://localhost:27017/NoteLink'
var mongoUtil = require('../mongoUtil');
var db = mongoUtil.getDb();
var nodemailer = require('nodemailer');
//for the nodemailer
var fileextensions = ['.doc','.docx','.pdf', '.txt'];
var ext;

/* GET home page. */
router.get('/', ensureAuthenticated, function (req, res, next) {
  //Andre, these commands might be of use, with the file path issue w/nodemailer
  //console.log(__dirname); //returns the current working directory
  //console.log(process.pwd()); //returns the directory that Node is executed froma
  res.render('apply')
  //hello();
})

  //How to create your own functions 
  function hello() {
    console.log('hello')
  }


router.post('/', ensureAuthenticated, function (req, res, next) {
  var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    //auth is the sender
    auth: {
      user: 'notelinkverify@gmail.com',
      pass: 'dre&will'
    }
  })
  for(var i = 0; i < fileextensions.length; i++) {
    if(req.body.transcript.includes(fileextensions[i])) {
      ext = fileextensions[i];
    }
  }
  let mailOptions = {
    from: 'notelinkverify@gmail.com',
    to: 'notelinkverify@gmail.com',
    subject: 'Applying for Tutor',
    attachments: [{
      filename: 'Transcript' + ext,
      path: req.body.transcript //BUG: attaches file, but it is empty
    }],
    text: 'Class request: ' + req.body.ApplyForClass + "\n"
          + 'Response: ' + req.body.Question + "\n" 
          + 'Email: ' + req.body.Email + "\n"
  }

    //Create a function here that checks the validity of the email

    transporter.sendMail(mailOptions, function(error, info) {
      if (error) {
        return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);
      console.log('file path? %s', req.body.transcript)
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    })





      req.flash('success', 'Tutor status: pending');
      res.redirect('/home');

})

function ensureAuthenticated(req, res, next){
 if(req.isAuthenticated()){
  return next();
 }
 res.redirect('/users/login');
}
module.exports = router;

apply.JS версия 2

/**
If the emailer still does not work, then one of us will have to do a COMPLETE rehaul
on the fiel structure so, that we can make it work.
*/

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb')
var assert = require('assert')
var url = 'mongodb://localhost:27017/NoteLink'
var mongoUtil = require('../mongoUtil');
var db = mongoUtil.getDb();
var nodemailer = require('nodemailer');
//for the nodemailer
var fileextensions = ['.doc','.docx','.pdf', '.txt'];
var ext;

/* GET home page. */
router.get('/', ensureAuthenticated, function (req, res, next) {
  //Andre, these commands might be of use, with the file path issue w/nodemailer
  //console.log(__dirname); //returns the current working directory
  //console.log(process.pwd()); //returns the directory that Node is executed froma
  res.render('apply')
  //hello();
})

  //How to create your own functions 
  function hello() {
    console.log('hello')
  }


router.post('/', ensureAuthenticated, function (req, res, next) {
  var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    //auth is the sender
    auth: {
      user: 'notelinkverify@gmail.com',
      pass: 'dre&will'
    }
  })
  for(var i = 0; i < fileextensions.length; i++) {
    if(req.body.transcript.includes(fileextensions[i])) {
      ext = fileextensions[i];
    }
  }
  let mailOptions = {
    from: 'notelinkverify@gmail.com',
    to: 'notelinkverify@gmail.com',
    subject: 'Applying for Tutor',
    attachments: [{
      filename: 'Transcript' + ext,
      path: req.body.transcript //BUG: attaches file, but it is empty
    }],
    text: 'Class request: ' + req.body.ApplyForClass + "\n"
          + 'Response: ' + req.body.Question + "\n" 
          + 'Email: ' + req.body.Email + "\n"
  }

    //Create a function here that checks the validity of the email

    transporter.sendMail(mailOptions, function(error, info) {
      if (error) {
        return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);
      console.log('file path? %s', req.body.transcript)
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    })





      req.flash('success', 'Tutor status: pending');
      res.redirect('/home');

})

function ensureAuthenticated(req, res, next){
 if(req.isAuthenticated()){
  return next();
 }
 res.redirect('/users/login');
}
module.exports = router;

Apply.JS Version 2 Command Prompt

{ [Error: ENOENT: no such file or directory, open 'C:\NoteLink\Psychology CAP pa
per.docx']
  errno: -4058,
  code: 'ESTREAM',
  syscall: 'open',
  path: 'C:\\NoteLink\\Psychology CAP paper.docx',
  command: 'API' }
...