2017-07-01 44 views
1

我笨上工作,我使用Mailgun API發送emails.But同時呼應curl_exe()我收到FORBIDDEN所示代碼:如何在CodeIgniter中使用Mailgun API;在curl_exe禁止錯誤()

<?php 
Class Email3 extends CI_Controller 
    { 
     function __construct() 
     { 
      parent::__construct(); 
     } 
     function index() { 
     $ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13'; 


       $ch = curl_init(); 
       curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 

       curl_setopt($ch, CURLOPT_USERPWD, 'my-api-key'); 
       curl_setopt($ch, CURLOPT_HEADER, true); 

       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
       curl_setopt($ch, CURLOPT_USERAGENT, $ua); 
       curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 
       curl_setopt($ch, CURLOPT_URL, 
          'https://api.mailgun.net/v2/samples.mailgun.org/messages'); 
       curl_setopt($ch, CURLOPT_POSTFIELDS, 
          array('from' => 'mymail', 
            'to' => 'othermail', 
            'subject' => 'The Printer Caught Fire', 
            'text' => 'We have a problem.')); 
       $result = curl_exec($ch); 
       curl_close($ch); 
       echo $result; 
      } 

    } 


?> 

我GOOGLE了它作爲很好搜索過SO也無法得到解決方案。請幫助我。 還發送電子郵件。

回答

0

這裏有一個簡單的CI庫,您可以使用:

應用程序/庫/ Mailgun.php

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class Mailgun { 

    protected $CI; 
    private static $api_key; 
    private static $api_base_url; 

    public function __construct() { 
    // assign CI super object 
    $this->CI =& get_instance(); 

    // config 
    self::$api_key = "key-XXXXX"; 
    self::$api_base_url = "https://api.mailgun.net/v3/mg.example.com"; 
    } 

    /** 
    * Send mail 
    * $mail = array(from, to, subject, text) 
    */ 
    public static function send($mail) { 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
    curl_setopt($ch, CURLOPT_USERPWD, 'api:' . self::$api_key); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 
    curl_setopt($ch, CURLOPT_URL, self::$api_base_url . '/messages'); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $mail); 
    $result = curl_exec($ch); 
    curl_close($ch); 
    return $result; 
    } 

} 
在你的控制器

然後:

應用/控制器/ Email.php

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class Email extends CI_Controller { 

    public function index() { 
    $this->load->library('mailgun'); 
    $this->mailgun::send([ 
     'from' => "Example.com team <[email protected]>", 
     'to' => "[email protected]", 
     'subject' => "Welcome to Example.com", 
     'text' => "We just want to say hi. Have fun at Example.com" 
    ]); 
    } 

} 

您必須使用有效的API密鑰和基礎URL才能正常工作。

相關問題