繁体   English   中英

nodemailer:无法发送pdf附件

[英]nodemailer: cannot send pdf attachment

我刚刚开始学习javascript,我想尝试构建一些小项目,以防万一。 作为我的第一个步骤,我正在构建一个命令行工具,该工具将发送pdf附件。 脚本应根据传递给javascript的参数发送带有pdf附件的电子邮件。 由于我想从命令行接受参数,因此通过谷歌搜索发现了一些代码 ,并对其进行了调整以满足我的需求。 我已经在下面包含了我正在使用的代码。 应该以pdf文件名(test.pdf)作为参数,然后将电子邮件发送给附带该文件的指定收件人。 如果使用所示的代码运行它,我会收到电子邮件,但收到的附件显示为“ undefined.pdf”,无法打开。

仅当我更改path: '/home/user/attachments/' + myArgs[3],行才有效path: '/home/user/attachments/' + myArgs[3], path: '/home/user/attachments/test.pdf',这会破坏脚本的要点,因为我不想对“路径”中的文件名进行硬编码以附加pdf文件。
(为了进行测试,我从与附件\\ home \\ user \\ attachments相同的目录中运行脚本。)

谁能指出我做错了什么? 我是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克里斯

让我们假设,您从控制台运行了这样的命令:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM