gpt4 book ai didi

node.js - 如何在 `Node aws-sdk` sendRawEmail 函数中发送 PDF 附件?

转载 作者:搜寻专家 更新时间:2023-11-01 00:20:02 24 4
gpt4 key购买 nike

我想使用 sendRawEmail(Node: aws-sdk) 函数发送附件中的 PDF 文件,我尝试了很多方法,电子邮件发送成功但 PDF 变得平淡无奇。请更正我的代码并帮助解决它。

代码在这里:

try {
data = fs.readFileSync('files/demo-invoice-new.pdf', 'utf8');

console.log(data.toString());

var ses_mail = "From: 'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">\n";
ses_mail = ses_mail + "To: " + toEmail + "\n";
ses_mail = ses_mail + "Subject: AWS SES Attachment Example\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 + "This is the body of the email.\n\n";
ses_mail = ses_mail + "--NextPart\n";
ses_mail = ses_mail + "Content-Type: application/octet;\n";
ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"demo-invoice-new.pdf\"\n\n";
ses_mail = ses_mail + data.toString('utf8') + "\n\n";
ses_mail = ses_mail + "--NextPart--";

var params = {
RawMessage: { Data: new Buffer(ses_mail) },
Destinations: [toEmail],
Source: "'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">'"
};

console.log(params);

var sendPromise = new AWS.SES(AWS_SES_CONFIG).sendRawEmail(params).promise();

return sendPromise.then(
data => {
console.log(data);
return data;
}).catch(
err => {
console.error(err.message);
throw err;
});
} catch (e) {
console.log('Error:', e.stack);
}

最佳答案

SES 原始消息 must be base64-encoded .因此,您需要获取文件内容作为缓冲区并将其编码为 base64 字符串附件。此外,您不需要为原始消息数据创建新缓冲区,因为它已经接受字符串数据类型。

可选:您也可以省略 Destinations 参数,因为您已经在原始消息数据中提供了 To 字段。 (您还可以提供 CcBcc 字段)

你可以试试这个,例如:

data = fs.readFileSync("files/demo-invoice-new.pdf");

var ses_mail = "From: 'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">\n";
ses_mail += "To: " + toEmail + "\n";
ses_mail += "Subject: AWS SES Attachment Example\n";
ses_mail += "MIME-Version: 1.0\n";
ses_mail += "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";
ses_mail += "--NextPart\n";
ses_mail += "Content-Type: text/html\n\n";
ses_mail += "This is the body of the email.\n\n";
ses_mail += "--NextPart\n";
ses_mail += "Content-Type: application/octet-stream; name=\"demo-invoice-new.pdf\"\n";
ses_mail += "Content-Transfer-Encoding: base64\n";
ses_mail += "Content-Disposition: attachment\n\n";
ses_mail += data.toString("base64").replace(/([^\0]{76})/g, "$1\n") + "\n\n";
ses_mail += "--NextPart--";

var params = {
RawMessage: {Data: ses_mail},
Source: "'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">'"
};

注意:/([^\0]{76})/ 正则表达式替换会打断您的长行以确保邮件服务器不会提示消息存在编码附件时行太长,这可能会导致瞬时反弹。 (参见 RFC 5321)

关于node.js - 如何在 `Node aws-sdk` sendRawEmail 函数中发送 PDF 附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com