WJ_Sparkpost

The MailPoet Newsletters WJ Sparkpost class.

Defined (1)

The class is defined in the following location(s).

/classes/WJ_Sparkpost.php  
  1. class WJ_Sparkpost { 
  2. public $error; 
  3. private $api_key = ''; 
  4.  
  5. public function __construct($api_key) { 
  6. $this->api_key = $api_key; 
  7.  
  8. public function send_mail(& $object) { 
  9. $msg = array( 
  10. 'recipients' => array( 
  11. array( 
  12. 'address' => array( 
  13. 'email' => $object->to[0][0] 
  14. ),  
  15. 'content' => array( 
  16. 'from' => array( 
  17. 'name' => $object->FromName,  
  18. 'email' => $object->From 
  19. ),  
  20. 'reply_to' => $object->ReplyTo[0][0] 
  21. ); 
  22.  
  23. // set the subject 
  24. if(!empty ($object->Subject)) $msg['content']['subject'] = $object->Subject; 
  25.  
  26. // set the body 
  27. if(!empty ($object->sendHTML) || !empty($object->AltBody)) { 
  28. $msg['content']['html'] = $object->Body; 
  29. if(!empty ($object->AltBody)) $msg['content']['text'] = $object->AltBody; 
  30. } else { 
  31. $msg['content']['text'] = $object->Body; 
  32.  
  33. $url = 'https://api.sparkpost.com/api/v1/transmissions'; 
  34.  
  35. return $this->run($url, $msg); 
  36.  
  37.  
  38. protected function run($url, $msg) { 
  39. $return = null; 
  40. $params = array( 
  41. 'headers' => array( 
  42. 'Content-Type: application/json',  
  43. 'Authorization' => $this->api_key 
  44. ),  
  45. 'body' => json_encode($msg) 
  46. ); 
  47.  
  48. $result = null; 
  49. $result = wp_remote_post($url, $params); 
  50. try { 
  51. if(!is_wp_error($result)) { 
  52. switch($result['response']['code']) { 
  53. case 200: 
  54. $return = true; 
  55. break; 
  56. default: 
  57. $body = json_decode($result['body'], true); 
  58. if(isset($body['errors']) && isset($body['errors'][0]) && isset($body['errors'][0]['description'])) { 
  59. $this->error = $body['errors'][0]['description']; 
  60. } else { 
  61. $this->error = $result['response']['message']; 
  62. break; 
  63. } else { 
  64. $this->error = (is_wp_error($result)) ? 
  65. $result->get_error_messages() : 
  66. __('We were unable to contact the API, the site may be down. Please try again later.', WYSIJA); 
  67. } catch(Exception $e) { 
  68. $this->error = 'Unexpected error: ' . $e->getMessage() . ' [' . var_export($result, true) . ']';// do nothing 
  69.  
  70. return $return; 
  71.