我想将URL附加到电子邮件中,我使用了一些解决方案,例如通过请求获取pdf URL或将其读取为文件,但是没有用。
@thinkingserious我通过下载pdf url修复了它,然后读取文件并将其附加到邮件中,但这不是一个好方法!
这是我的示例代码,这仅用于测试:)
谢谢
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
var download = require('download-file'),
fs = require('fs'),
array = [],
temp = [],
files = [];
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf');
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf');
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf');
array.forEach(function(url) {
temp++;
var options = {
directory: "./pdf",
filename: temp.toString() + Date.now() + ".pdf"
};
download(url, options, function(err, res) {
console.log( __dirname + '/pdf/' + options.filename );
files.push(res);
if ( array.length == files.length ) {
// console.log( "hello" );
var counter = 0,
attach = [];
files.forEach( function(name, index) {
name = name.substring(1, name.length );
fs.readFile(__dirname + name, function(err, file) {
console.log( file );
var base64File = new Buffer(file).toString('base64');
counter++;
attach.push({
content : base64File,
filename : 'Report.pdf'
});
console.log( attach );
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Test',
text: 'this is test',
html: '<strong>Hello World</strong>',
attachments: attach,
};
// console.log( msg );
if ( counter == files.length )
sgMail.send(msg);
});
});
}
});
});
@thinkingserious我对其进行了测试,但PDF文件有时不正确并且在邮件附件中不可读。
谢谢
request = require('request');
request.get( url, function(err, res) {
var base64File = new Buffer(res.body).toString('base64');
...
});
嗨@ShahrokhNiakan ,
您要使用相同或不同的PDF进行测试吗?
在无法读取PDF的情况下,是否可以验证源PDF是否未损坏?
@ShahrokhNiakan因为pdf是二进制而不是字符串,所以我认为您应该在传递给请求的选项中指定encoding: null
,这样请求库就不会尝试将其解码为utf-8字符串。
例如:
request = require('request');
request.get( url, { encoding: null } function(err, res) {
var base64File = new Buffer(res.body).toString('base64');
...
});
从请求的
encoding-用于响应数据的setEncoding的编码。 如果为null,则将正文作为Buffer返回。 其他任何内容(包括默认值undefined)都将作为编码参数传递给toString()(这意味着默认情况下它实际上是utf8)。 (注意:如果需要二进制数据,则应将编码设置为:null。 )
@brafdlog您的解决方案对我
较早的SendGrid模块支持指定附件的URL。 那很方便。 为什么每个发送者都烦恼发送大量的base64内容。 Sendgrid应该能够做到这一点。
最有用的评论
@ShahrokhNiakan因为pdf是二进制而不是字符串,所以我认为您应该在传递给请求的选项中指定
encoding: null
,这样请求库就不会尝试将其解码为utf-8字符串。例如:
从请求的