我需要创建一个通过Amazon SES发送html电子邮件的api。我已正确创建了ses凭证,并且想在javascript(nodejs)中创建一个AWS lambda。由于缺乏良好的AWS文档来使用javascript发送电子邮件,我需要知道如何创建一个lambda来发送电子邮件并以适当的消息响应到AWS api网关。
答案 0 :(得分:-1)
以下是用javascript编写的代码。在AWS Lambda上运行完美,并且在从AWS Api网关调用时运行良好(没有格式错误的消息错误):
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);
});
};