我正在使用Express中的简单webhook在特定事件中通过Mailgun发送PDF。但是,每当我尝试发送它时,都会收到此错误:{[错误:'来自'参数缺失] statusCode:400}。我用简单的.txt文件对它进行了测试,它工作正常,所以我假设它与PDF附件有关。我的代码在这里:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var PDFDocument = require('pdfkit');
var mg = require('nodemailer-mailgun-transport');
var fs = require('fs');
app.use(bodyParser.json());
app.post('/', function(req, res) {
generatePDF(req.body.line_items);
if (req.body.line_items) {
sendMail();
res.send('OK');
}
});
app.listen(3030, function() {
console.log('test app listening on port 3030');
});
function generatePDF(lineItems) {
var doc = new PDFDocument();
var writeStream = fs.createWriteStream('mailer/output.pdf');
doc.pipe(writeStream);
for (item in lineItems) {
for (key in item) {
doc.text(item[key]);
}
}
console.log("doc: " + doc);
doc.end();
}
function sendMail() {
var auth = {
auth: {
api_key: 'my-key',
domain: 'my-domain'
}
}
var transporter = nodemailer.createTransport(mg(auth));
var mailOptions = {
from: 'my-email',
to: 'their-email',
subject: 'test',
html: '<b>this is a test</b>',
attachments: [
{
filename: 'output.pdf',
path: 'mailer/output.pdf',
content: 'output mailer'
}
],
}
transporter.sendMail(mailOptions, function(error, info){
console.log('mail sent');
if (error) {
return console.error(error)
}
console.log('success!', info);
})
}
非常感谢任何帮助!
答案 0 :(得分:1)
忘了发布我的解决方案,但是这里对于遇到这个问题的未来人来说是迟来的。在我发送之前,writeStream没有完成,并且nodemailer变得非常困惑,所以我插入了一个条件,即PDF(或任何文档)在发送之前完成写入。
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var PDFDocument = require('pdfkit');
var mg = require('nodemailer-mailgun-transport');
var fs = require('fs');
var idStorage = [];
app.use(bodyParser.json());
app.post('/', function(req, res) {
var JSON = req.body;
console.log(idStorage);
if (req.body.line_items) {
res.sendStatus(200);
generatePDF(JSON);
}
});
app.listen(3030, function() {
console.log('example app listening on port 3030');
});
function generatePDF(JSON) {
//create doc and doc variables
var doc = new PDFDocument();
var writeStream = fs.createWriteStream('mailer/output.pdf');
doc.pipe(writeStream);
//write whatever you want to the PDF
doc.save();
//wait for the PDF to finish writing before you send it.
writeStream.on('finish', function() {
sendMail(JSON);
});
}
doc.end();
}
}
function sendMail(JSON) {
var auth = {
auth: {
api_key: 'key',
domain: 'domain.com'
}
}
var transporter = nodemailer.createTransport(mg(auth));
var mailOptions = {
from: 'me',
to: 'you',
subject: JSON.id,
html: '<b>Test</b>',
attachments: [
{
filename: 'output.pdf',
path: 'mailer/output.pdf'
}
],
}
transporter.sendMail(mailOptions, function(error, info){
console.log('mail sent');
if (error) {
return console.error(error)
}
console.log('success!', info);
})
}
}