2013-05-15 24 views
1

我正在用phantomjs做一些屏幕抓取。我試圖實現一個錯誤處理系統,當刮板失敗時發送一個包含mandrill api https://mandrillapp.com/api/docs/messages.html的電子郵件。你會如何發送郵件通過mandrill phantomjs?

mandrill api採用後面的方法。 你將如何通過幻影通過mandrill發送郵件?

var data = { 
    "key": "VdFwNvj-dLwaI6caAh8ODg", 
    "message": { 
     "html": "This aggression will not stand", 
     "text": "This aggression will not stand", 
     "subject": "example subject", 
     "from_email": "[email protected]", 
     "from_name": "The Dude", 
     "to": [{ 
      "email": "[email protected]", 
      "name": "lebowski" 
     }] 
    }, 
    "async": false 
}; 

$.ajax({ 
    type: "POST", 
    url: 'https://mandrillapp.com/api/1.0/messages/send.json', 
    data: data 
}); 

回答

0

最簡單的方法是旋轉了一個新的頁面,使一個REST調用,那麼您可以使用page.evaluate讀結果。雖然它不像jQuery ajax方法那麼簡單,但您可以輕鬆創建對象來簡化其使用。

var page = require('webpage').create(), 
    url = 'https://mandrillapp.com/api/1.0/messages/send.json', 
    data = { 
    "key": "VdFwNvj-dLwaI6caAh8ODg", 
    "message": { 
     "html": "This aggression will not stand", 
     "text": "This aggression will not stand", 
     "subject": "example subject", 
     "from_email": "[email protected]", 
     "from_name": "The Dude", 
     "to": [{ 
      "email": "[email protected]", 
      "name": "lebowski" 
     }] 
    }, 
    "async": false 
}; 

page.open(url, 'POST', data, function (status) { 
    if (status !== 'success') { 
     console.log('FAIL to load the log'); 
    } else { 
     console.log('Log success'); 

     var result = page.evaluate(function() { 
      return document.body.innerText; 
     }); 

     console.log("log Result: " + result); 
    }  
}); 
3

我花了一段時間試圖找到答案工作沒有喜悅。我結束了測試:http://httpbin.org/post找出爲什麼mandril未能處理我的請求,結果數據沒有正確發送。 PhantomJS文檔也不正確。正是這樣的例子:https://github.com/adrianchung/phantomjs/blob/069ab5dea4c07c61a0ac259df0ff219ade1e8225/examples/postjson.js最終給了我失蹤的一塊。山魈文檔也非常有用:https://mandrillapp.com/api/docs/messages.JSON.html

我完成代碼:

var page = require('webpage').create(); 
var email_url = 'https://mandrillapp.com/api/1.0/messages/send.json'; 
//email_url = 'http://httpbin.org/post'; // When testing 

var email_data = { 
    key: "your-key", 
    "message": { 
     "text": email_message_text, 
     "subject": "Your subject", 
     "from_email": "your email", 
     "from_name": "Kris", 
     "to": [{ 
      "email": "your email", 
      "name": "Kris" 
     }] 
    }, 
    "async": false 
}; 
var email_headers = { 
    "Content-Type": "application/json" 
}; 

page.open(
    email_url, 
    'post', 
    JSON.stringify(email_data), // You need to stringify the json or it doesn't work 
    email_headers, 
    function (status) { 

     if (status !== 'success') { 
      PrintError('FAIL to email results'); 
     } else {   
      var result = page.evaluate(function() { 
         return document.body.innerText; 
        }); 
      Print('Email successfully sent\n' + result); 
     }  
     phantom.exit(); 
    } 
);