nodemailer:无法发送pdf附件

时间:2015-12-23 20:26:09

标签: javascript node.js nodemailer

我刚刚开始学习javascript,我想尝试建立一些小项目,以便脚踏实地。作为我第一次尝试的一部分,我正在构建一个命令行工具,它将发送pdf附件。该脚本应根据传递给javascript的参数发送带有pdf附件的电子邮件。我通过谷歌搜索发现了一些code并调整它以满足我的需求,因为我想从命令行接受参数。我已经在下面使用了代码I' m。它应该将pdf文件名(test.pdf)作为参数,然后将电子邮件发送给附加了该文件的指定收件人。如果我使用我的代码运行它,如图所示,我会收到电子邮件,但收到的附件中显示" undefined.pdf"并且无法打开。

只有当我将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, 克里斯

1 个答案:

答案 0 :(得分:1)

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

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
相关问题