AWS SES,电子邮件附件发送base64字符串,而不是转换为DOCX格式

时间:2019-01-17 15:07:50

标签: amazon-web-services amazon-ses serverless-framework serverless aws-serverless

要求

我想做的是,首先要从S3存储桶下载一个文档,然后通过SES发送该文档,并使用sendRawEmail方法作为从S3下载的文件的附件。

我到目前为止所做的事情

我已经从S3下载了文件,我可以发送带有附件的邮件。它按预期到达了目的地(form.docx)

错误

发送附件时,必须在formdata中附加base64(即附件)字符串。我附上了绳子。但是当我下载附件时。在form.docx里面,我可以看到附件中有转换后的base64字符串。这不是预期的。我应该看到表格和一些填补空白的东西。但这是一个很大的base64字符串

代码

const AWS = require('aws-sdk');
const S3= new AWS.S3();
let ses = new AWS.SES();
exports.hello = async (event, context) => {
  try {
    const valueFromBucket = await S3.getObject({Bucket: '*******', Key: 'form.docx'}).promise();
    var buffer = valueFromBucket.Body.toString('base64');
    var message = '<html><body ><div> This is a test Message</div></body></html>';
    var fromEmail = '******@gmail.com';
    var toEmail = '*******@gmail.com';
    var ses_mail = "From: 'Email' <" + fromEmail + ">\n";
    ses_mail = ses_mail + "To: " + toEmail + "\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=iso-8859-1\n\n";
    ses_mail = ses_mail + message+"\n";
    ses_mail = ses_mail + "--NextPart\n";
    ses_mail = ses_mail + "Content-Type: application/msword\n";
    ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"form.docx\"\n\n";
    ses_mail = ses_mail + "Content-Transfer-Encoding: base64\n\n"
    ses_mail = ses_mail + buffer + "\n";
    ses_mail = ses_mail + "--NextPart--";

    var params = {
        RawMessage: { Data: new Buffer(ses_mail)},
        Destinations: [ "*******@gmail.com" ],
        Source: "'AWS Tutorial Series' <" + fromEmail + ">'"
    };
    const sendPromise = await new AWS.SES({ apiVersion: "2010-12-01" })
    .sendRawEmail(params)
    .promise();
    return{
      statusCode: 200,
      body: JSON.stringify(sendPromise)
    }
  }
  catch (err) {
    return {
      statusCode: err.statusCode || 400,
      body: err.message || JSON.stringify(err.message)
    }
  }
}

非常感谢任何帮助或建议

预先感谢

1 个答案:

答案 0 :(得分:2)

问题是您的代码为您的部分部件标题中的两个换行符。

更改此行代码:

ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";

对此:

ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n";