【问题标题】:nodemailer: cannot send pdf attachmentnodemailer:无法发送pdf附件
【发布时间】:2016-03-30 07:57:36
【问题描述】:

我刚开始学习 javascript,我想尝试构建一些小项目来熟悉一下。作为我第一次尝试的一部分,我正在构建一个命令行工具,它将发送 pdf 附件。该脚本应根据传递给 javascript 的参数发送带有 pdf 附件的电子邮件。我通过谷歌搜索找到了一些code 并对其进行了调整以满足我的需求,因为我想接受来自命令行的参数。我在下面包含了我正在使用的代码。它应该将 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, 克里斯

【问题讨论】:

  • console.log 行(第 3 行)打印什么?

标签: javascript node.js nodemailer


【解决方案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

【讨论】:

  • 非常感谢拉扎列夫!就是这样。将 myArgs[3] 更改为 'myArgs[0]' 现在可以使用了。
  • @LazarevAlexandr 你如何解释允许人们上传他们的 PDF 文件并附加附件? path 会是什么?它显然不是本地文件系统路径
  • @Growler 我假设您有一台服务器正在为此运行。只需创建一个将接收带有所需文件的多部分数据的路由,将文件保存到某个 tmp 目录并在 nodemailer 的帮助下发送。
猜你喜欢
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-15
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
相关资源
最近更新 更多