nodemailer:不能发送pdf附件

我刚刚开始学习JavaScript,我想尝试build立一些小项目,通过脚湿。 作为我的第一个刺的一部分,我正在构build一个命令行工具,将发送PDF附件。 该脚本应该发送电子邮件与基于传递给JavaScript的参数的PDF附件。 我发现了一些代码search,并调整它来满足我的需求,因为我想接受来自命令行的参数。 我已经包含了我在下面使用的代码。 它应该将pdf文件名(test.pdf)作为参数,然后将电子邮件发送给附加了该文件的指定收件人。 如果我用我的代码运行它,如图所示,我收到电子邮件,但收到的附件说“undefined.pdf”,无法打开。

它只有当我改变path: '/home/user/attachments/' + myArgs[3],path: '/home/user/attachments/' + myArgs[3], path: '/home/user/attachments/test.pdf',它毁坏脚本的点我不想在“path”附加PDF文件的硬编码文件名。
(为了testing,我正在从附件\ home \ user \附件的相同目录运行脚本。)

任何人都可以指出我做错了什么? 我是一个新手到JavaScript,所以我猜我错过了一些显而易见的事情:] ….

 var nodemailer = require('nodemailer'); var myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); // create reusable transporter object using SMTP transport var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'somebody@gmail.com', pass: 'secret' } }); // NB! No need to recreate the transporter object. You can use // the same transporter object for all e-mails // setup e-mail data with unicode symbols var mailOptions = { from: 'Somebody <somebody@gmail.com>', // sender address to: 'you@random.org, dude@blahblah.com', // list of receivers subject: 'Hello', // Subject line text: 'Hello world', // plaintext body html: '<b>Hello world</b>', // html body attachments: [ { // filename and content type is derived from path filename: myArgs[3], path: '/home/user/attachments/' + myArgs[3], contentType: 'application/pdf' } ] }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); }); 

TIA,Chris

让我们假设,你从控制台运行这样一个命令:

 node script.js file.pdf 

process.argv返回一个包含命令行参数的数组。 所以,这将是:

 process.argv[0] = 'node' process.argv[1] = 'path/to/script.js' process.argv[2] = 'file.pdf 

通过应用slice(2)process.argv转换成一个只有一个元素的数组:

 process.argv[0] = 'file.pdf'; 

所以,最有可能的是你应该把myArgs[3] myArgs[0]或者你应该添加更多的参数,使file arg成为第六个。 例如:

 node script.js to@email.com from@email.com email subject file.pdf