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

时间:2018-03-19 13:30:14

标签: node.js amazon-web-services aws-sdk email-attachments amazon-ses

我想使用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);
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

您好,对于那些偶然发现此问题的人,我设法使用nodemailerSESV2解决了这个问题,我拥有base64编码的数据,因此您的脚本可能与我的有所不同,但是下面的代码段应该给您一个主意...这是我的解决方案,希望对您有所帮助:

const MailComposer = require("nodemailer/lib/mail-composer");
const AWS = require("aws-sdk");

const generateRawMailData = (message) => {
    let mailOptions = {
        from: message.fromEmail,
        to: message.to,
        subject: message.subject,
        text: message.bodyTxt,
        html: message.bodyHtml,
        attachments: message.attachments.map(a => ({ filename: a.name, content: a.data, encoding: 'base64' }))
    };
    return new MailComposer(mailOptions).compile().build();
};

const exampleSendEmail = async () => {
    var message = {
        fromEmail: "sender@server.com",
        to: "receiver@sender.com",
        subject: "Message title",
        bodyTxt: "Plaintext version of the message",
        bodyHtml: "<p>HTML version of the message</p>",
        attachments: [{
            name: 'hello.txt',
            data: 'aGVsbG8gd29ybGQ='
        }]
    };

    let ses = new AWS.SESV2(),
    params = {
      Content: { Raw: { Data: await generateRawMailData(message) } },
      Destination: {
        ToAddresses: message.to,
        BccAddresses: message.bcc,
      },
      FromEmailAddress: message.fromEmail,
      ReplyToAddresses: message.replyTo,
    };

  return ses.sendEmail(params).promise();
}