Last active
September 17, 2018 08:11
-
-
Save andreasonny83/b4fc82570b498c170a672adb886e7295 to your computer and use it in GitHub Desktop.
sendMail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2018 AndreaSonny <[email protected]> (https://github.com/andreasonny83) | |
// | |
// This software is released under the MIT License. | |
// https://opensource.org/licenses/MIT | |
'use strict'; | |
const AWS = require('aws-sdk'); | |
const ses = new AWS.SES(); | |
require('dotenv').config(); | |
const from = process.env.FROM; | |
const to = process.env.TO; | |
const subject = process.env.SUBJECT; | |
const debug = process.env.DEBUG === 'true'; | |
class EmailSenderError extends Error { | |
constructor(...params) { | |
super(...params); | |
this.name = 'EmailSenderError'; | |
Error.captureStackTrace(this, EmailSenderError); | |
} | |
} | |
function generateError(err, statusCode) { | |
const error = new EmailSenderError(err); | |
return { | |
statusCode, | |
headers: { | |
'Content-Type': 'application/json', | |
'Access-Control-Allow-Origin': '*', | |
'Access-Control-Allow-Credentials': true, | |
}, | |
body: JSON.stringify({ | |
name: error.name, | |
message: error.message, | |
}), | |
}; | |
} | |
const prepareEmail = (subject, from, to) => ({ | |
Destination: { | |
ToAddresses: [to], | |
}, | |
Message: { | |
Subject: { | |
Data: subject, | |
Charset: 'UTF-8', | |
}, | |
Body: { | |
Text: { | |
Data: 'this is a test email', | |
Charset: 'UTF-8', | |
}, | |
}, | |
}, | |
Source: from, | |
}); | |
module.exports.send = async (event, context) => { | |
const params = prepareEmail(subject, from, to); | |
let data = event.body; | |
let sendEmail; | |
try { | |
data = JSON.parse(data); | |
} catch (err) { | |
return generateError(err, 500); | |
} | |
if (debug) { | |
console.log('event received'); | |
console.log(JSON.parse(data)); | |
} | |
try { | |
sendEmail = await ses.sendEmail(params).promise(); | |
} catch (err) { | |
return generateError(err, 500); | |
} | |
return { | |
statusCode: 200, | |
headers: { 'Access-Control-Allow-Origin': '*' }, | |
body: JSON.stringify({ | |
status: 'success', | |
}), | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment