Send Email from PhantomJS
I was looking for a way to run automated tests on Javascript, and one of the key requirements of automated tests, are that the results are communicated back. As long as I’m just looking for erroneous / exceptional events then email is a great way to get my attention. But I wanted to find an online service that would provide this for me, rather than writing my own server side code, so I tried a few, and came up with mailgun.net
function ObjToQs(obj)
{
str = ”;
for(key in obj) {
str += key + ‘=’ + obj[key] + ‘&’;
}
str = str.slice(0, str.length – 1);
return str;
}var page = require(‘webpage’).create(),
url = ‘https://api.mailgun.net/v2/sandboxed7c45b35fc04752931f87faecae4428.mailgun.org/messages’,
data = {
“from” : “Mailgun Sandbox <postmaster@sandboxed7c45b35fc04752931f87faecae4428.mailgun.org>”,
“to” : “xxxx@gmail.com”,
“subject” : “Hello!”,
“text”: “Test from mailgun / phantomjs”
};page.customHeaders={‘Authorization’: ‘Basic ‘+btoa(‘api:key-xxxxxx’)};
page.open(url, ‘post’, ObjToQs(data), function (status) {
if (status !== ‘success’) {
console.log(‘FAIL to load the log’);
console.log(status);
} else {
console.log(‘Log success’);var result = page.evaluate(function () {
return document.body.innerText;
});console.log(“log Result: ” + result);
phantom.exit();
}
});
I’ve left out my API key, you can get your own at mailgun.net –
A successful result should be as follows:
C:\research\phantomjs>phantomjs errorreport.js
Log success
log Result: {
“message”: “Queued. Thank you.”,
“id”: “<20140422121333.32180.12028@sandboxed7c45b35fc04752931f87faecae4428.mai
lgun.org>”
}