在 S3 存储桶中附加图像以使用 SendGrid 发送

Attach image in S3 bucket to send with SendGrid

我正在使用 Xcode 7.3 在 Swift 2.2 中编写一个 iOS 应用程序。 1.然后,对于后端服务,我使用 AWS MobilehubS3Lambda

应用程序应该做什么:截取屏幕截图,将其发送到 AWS S3 存储桶,使用 SendGrid 发送屏幕截图AWS Lambda 函数触发器。

我的问题:我似乎无法将 S3 存储桶中该死的图像附加到电子邮件中。在本地它工作正常,但是当上传到 Lambda 时会抛出以下错误:

Error: ENOENT: no such file or directory, open '...'

使用以下代码:

'use strict';

var fs = require('fs');

console.log('Loading function');

let aws = require('aws-sdk');
let s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = (event, context, callback) => {

    // Get the object from the event and show its content type
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));

    var helper = require('sendgrid').mail;

    let from_email = new helper.Email("from@gmail.com");
    let to_email = new helper.Email("to@gmail.com");
    let subject = "Hello World from the SendGrid Node.js Library";
    let content = new helper.Content("text/plain", "Email content");

    let mail = new helper.Mail(from_email, subject, to_email, content);


    var bse64 = base64_encode(INeedThisFrigginPath);

    let attachment = new helper.Attachment();
    attachment.setContent(bse64);
    attachment.setType("image/png");
    attachment.setFilename(key);
    attachment.setDisposition("attachment");
    mail.addAttachment(attachment);

    var sg = require('sendgrid')('SG.sengridkey');

    var requestBody = mail.toJSON();
    var emptyRequest = require('sendgrid-rest').request;
    var requestPost = JSON.parse(JSON.stringify(emptyRequest));
    requestPost.method = 'POST';
    requestPost.path = '/v3/mail/send';
    requestPost.body = requestBody;
    sg.API(requestPost, 
            function (error, response) 
            {
                console.log(response.statusCode);
                console.log(response.body);
                console.log(response.headers);
            }
    );
};

// function to encode file data to base64 encoded string
function base64_encode(file) 
{
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

具体这一行:

var bse64 = base64_encode(INeedThisFrigginPath);

问题很明显,所以我需要知道的是,我的图像的正确路径是什么

我试过使用键值,图像 link:

https://s3.eu-central-1.amazonaws.com/bucketname/public/test0.png

运气不好。

如果有人可以通过提供代码、教程或只是一般性的指导来帮助我,帮助我朝着正确的方向前进,那就太好了。也许使用 AWS S3、AWS LambdaSendGrid 不一定是这里使用的最佳技术?

非常感谢!

您正在尝试构建该文件的路径,然后您正试图将其作为本地文件打开。该文件不是本地的,它在 S3 上,所以你不能这样做。您有两个选择:

  • 先从S3下载文件到Lambda(到/tmp目录下),打开文件时参考本地路径
  • 使用 AWS S3 SDK 打开文件的 ReadStream。