Skip to content

Instantly share code, notes, and snippets.

@ASteinheiser
Last active November 27, 2018 17:13
Show Gist options
  • Save ASteinheiser/cdae557318d6358a946752db976002e2 to your computer and use it in GitHub Desktop.
Save ASteinheiser/cdae557318d6358a946752db976002e2 to your computer and use it in GitHub Desktop.
AWS Lambda for my "contact me" form on my personal site, iamandrew.io
const aws = require('aws-sdk');
const ses = new aws.SES({ region: 'us-west-2' });
const MY_EMAIL = 'me@iamandrew.io';
exports.handler = async (event, context, callback) => {
console.log('event: ', event);
const response = {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
},
body: ''
};
switch(event.httpMethod) {
case 'POST':
const { name, email, subject, message } = JSON.parse(event.body);
if(!name || !email || !subject || !message) {
response.statusCode = 403;
response.body = JSON.stringify({message: 'Bad request'});
callback(null, response);
}
const params = {
Destination: {
ToAddresses: [MY_EMAIL]
},
Message: {
Body: {
Text: {
Data: `New Message from ${name} @ ${email}\n\n-----------------------------\n\n${message}`
}
},
Subject: {
Data: subject
}
},
Source: MY_EMAIL
};
console.log('sending email to: ', JSON.stringify(params));
ses.sendEmail(params, (err, data) => {
if(err) {
console.log('Error: ', err);
const message = err.message || 'An unknown error has occured...';
response.statusCode = 500;
response.body = JSON.stringify({message: message});
callback(null, response);
}
else {
console.log('email success: ', data);
response.body = JSON.stringify({message: 'Success'});
callback(null, response);
}
});
case 'OPTIONS':
callback(null, response);
default:
response.statusCode = 405;
response.body = JSON.stringify({message: 'Not a supported method.'});
callback(null, response);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment