如何在SES电子邮件中添加PDF附件 - 节点js

时间:2017-10-22 10:08:55

标签: node.js aws-lambda html-pdf amazon-ses

我正在使用NodeJs发送电子邮件(通过aws ses)附件pdf。目前我正在尝试在pdf附件中添加html内容。当我收到附件的pdf时,我无法打开pdf文件。我收到文件已损坏的错误。为了您的信息,我在这里添加了代码。如果我在此配置中缺少任何内容,请告诉我

var message = '<html><body ><div style="margin: auto; width: 96%; border: 6px solid black; vertical-align:middle; text-align:center;height:auto"><img style="width: 204px; height: 128px;" src="image.png" /></div></body></html>';

var ses_mail = "From: 'Email' <" + email + ">\n";
ses_mail = ses_mail + "To: " + email + "\n";
ses_mail = ses_mail + "Subject: Subject Email\n";
ses_mail = ses_mail + "MIME-Version: 1.0\n";
ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";
ses_mail = ses_mail + "--NextPart\n";
ses_mail = ses_mail + "Content-Type: text/html; charset=us-ascii\n\n";
ses_mail = ses_mail + message+"\n";
ses_mail = ses_mail + "--NextPart\n";
ses_mail = ses_mail + "Content-Type: application/pdf;\n";
ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"attachment.pdf\"\n\n";
ses_mail = ses_mail + "Content-Transfer-Encoding: utf-8\n\n"
ses_mail = ses_mail + message + "\n";
ses_mail = ses_mail + "--NextPart--";

var params = {
    RawMessage: { Data: new Buffer(ses_mail)},
    Destinations: [ email ],
    Source: "'AWS Tutorial Series' <" + email + ">'"
};

ses.sendRawEmail(params, function(err, data) {
    if(err) {
        console.log('failed');
    }
    else {
        console.log('success');
    }
});
});

1 个答案:

答案 0 :(得分:1)

您尝试添加的PDF内容是html消息,当然这不是PDF的有效内容。您可以做的是将PDF文件的内容作为缓冲区读取,然后将其编码为base64,然后将传输编码更改为base64

pdfContent = pdfBuffer.toString('base64');
ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"attachment.pdf\"\n\n";
ses_mail = ses_mail + "Content-Transfer-Encoding: base64\n\n"
ses_mail = ses_mail + pdfContent + "\n";