Skip to content

Instantly share code, notes, and snippets.

@mshuber1981
Last active June 26, 2022 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mshuber1981/9e95b9b83839d9e89740a6f8dcb482bf to your computer and use it in GitHub Desktop.
Save mshuber1981/9e95b9b83839d9e89740a6f8dcb482bf to your computer and use it in GitHub Desktop.
API Gateway Lambda (Node.js) proxy with SES example
// https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
const AWS = require("aws-sdk");
const ses = new AWS.SES();
// https://aws.amazon.com/premiumsupport/knowledge-center/lambda-send-email-ses/
const SENDER = "Your name <YourVerrifiedEmail@provider.com>";
function response(status, message) {
const res = {
isBase64Encoded: false,
headers: {
"Access-Control-Allow-Headers": "application/json",
"Access-Control-Allow-Origin": "https://www.ApprovedDomain.com", // https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
"Access-Control-Allow-Methods": "POST",
},
statusCode: status,
body: JSON.stringify(message),
};
return res;
}
function sendEmail(event, body, context, callback) {
const params = {
Destination: {
ToAddresses: [SENDER],
},
Message: {
Body: {
Text: {
Data:
"Name: " +
body.name +
"\nEmail: " +
body.email +
"\nMessage: " +
body.message,
Charset: "UTF-8",
},
},
Subject: {
Data: "Portfolio Contact Form: " + body.name,
Charset: "UTF-8",
},
},
Source: SENDER,
};
ses.sendEmail(params, function (err, data) {
callback(null, response(200, "Thank you, I will contact you soon."));
if (err) {
console.log(err);
context.fail(err);
} else {
console.log(data);
context.succeed(event);
}
});
}
function sendAutoReply(event, body, context) {
const params = {
Destination: {
ToAddresses: [`${body.email}`],
},
Source: SENDER,
Template: "TemplateName", // https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html#send-personalized-email-create-template
TemplateData: '{"message":"Thank you!"}',
ConfigurationSetName: "CongfigName",
};
ses.sendTemplatedEmail(params, function (err, data) {
if (err) {
console.log(err);
context.fail(err);
} else {
console.log(data);
context.succeed(event);
}
});
}
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
exports.handler = (event, context, callback) => {
// https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html
const domain = event.headers.origin;
const body = JSON.parse(event.body);
if (domain === "https://www.ApprovedDomain.com") {
sendEmail(event, body, context, callback);
sendAutoReply(event, body, context);
} else {
console.log(event.headers.origin);
return response(403, "Acess Denied");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment