简体   繁体   中英

How to send a html email in AWS Lambda node js returning a well formed response for AWS api gateway

I need to create an api that sends html emails through amazon SES. I created properly my ses credentials and I want to create an AWS lambda in javascript (nodejs). Due the lack of good AWS documentation for sending an email using javascript, I need to know how to create a lambda that sends an email and responds with a proper message to AWS api gateway.

The following was code written in javascript. Works perfect in AWS lambda and works great when is invoked from AWS Api gateway (no malformed message errors):

var aws = require("aws-sdk");
var ses = new aws.SES({
accessKeyId: "Your SES Access Key",
secretAccesskey: "Your Secret key",
region: "us-east-1" // CHANGE with the region where you configured SES
});

exports.handler = function(event, context, callback) {
var requestPath = JSON.parse(JSON.stringify(event.pathParameters));
var requestBody = JSON.parse(event.body);
var responseBody = {};
var response = {};

if (
requestBody &&
requestBody.emailFrom &&
requestBody.subject &&
requestBody.htmlBody
) {
var emailTo = requestPath.emailto;
var emailFrom = requestBody.emailFrom;
var subject = requestBody.subject;
var htmlBody = requestBody.htmlBody;
} else {
responseBody = {
    result: "fail",
    resultCode: 400,
    description:
    "Incorrect Parameters. Mandatory: emailFrom, subject and bodyHTML"
};

response = {
    statusCode: 400,
    headers: {
    "Access-Control-Allow-Origin": "*"
    },
    body: JSON.stringify(responseBody),
    isBase64Encoded: false
};

callback(null, response);
}

var emailParams = {
Destination: {
    ToAddresses: [emailTo]
},
Message: {
    Body: {
    Html: {
        Data: htmlBody
    }
    },
    Subject: {
    Data: subject
    }
},
Source: emailFrom
};


var email = ses.sendEmail(emailParams, function(err, data) {
var resultCode = 200;
if (err) {
    var responseBody = {
    result: "FAIL",
    resultCode: 500,
    description: "Error sending email: " + err
    };
    resultCode = 500;
} else {
    var responseBody = {
    result: "OK",
    resultCode: 200,
    description: "Email sent successfully"
    };
}



response = {
    statusCode: resultCode,
    headers: {
    "Access-Control-Allow-Origin": "*"
    },
    body: JSON.stringify(responseBody),
    isBase64Encoded: false
};
callback(null, response);
});
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM