Last active
March 12, 2018 19:23
-
-
Save huikang/ffe745aadbcfddbe1bd7e0abbdc94cfd to your computer and use it in GitHub Desktop.
wsk-send-email
This file contains 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
var request = require('request-promise'); | |
/** | |
* Triggered whenever data changes in the database | |
* | |
* @param params.id The id of the record in the Cloudant 'service' database, if invoked by a database change | |
* @param params.appliance The appliance object if invoked by the nightly alarm trigger | |
* @param params.SENDGRID_API_KEY SendGrid key for sending notifications | |
* @param params.SENDGRID_FROM_ADDRESS Address to set as sender | |
* @param params.SENDGRID_TO_ADDRESS Address to set as receiver | |
* @return Standard OpenWhisk success/error response | |
*/ | |
function main(params) { | |
email = params.SENDGRID_TO_ADDRESS; | |
subject = 'Alert from TSS-platform regarding IoT devices'; | |
content = 'ALERT ALERT '; | |
sequence = 'sequence'; | |
if (params.hasOwnProperty(sequence)) { | |
console.log('[alert-email] invoked with temperature sequence'); | |
content += 'Your device had abnormal temperature: ' + params[sequence] + '. '; | |
} | |
return send(email, subject, content, params) | |
.then(res => ({ | |
success: '[alert-customer-event.main] Success sending notification' | |
})) | |
.catch(err => ({ | |
error: '[alert-customer-event.main] Error sending notification: ' + err | |
})); | |
} | |
// Configure SendGrid (need to use request against the API directly) | |
function send(email, subject, content, params) { | |
return request({ | |
url: 'https://api.sendgrid.com/v3/mail/send', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': 'Bearer ' + params.SENDGRID_API_KEY | |
}, | |
body: '{"personalizations": [{"to": [{"email": "' + email + '"}]}],"from": {"email": "' + params.SENDGRID_FROM_ADDRESS + '"},"subject": "' + subject + '","content": [{"type": "text/plain", "value": "' + content + '"}]}' | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment