How to work with Mailgun API in CodeIgniter; Forbidden error in curl_exe()

大憨熊 提交于 2019-12-06 16:06:43

Here's a simple CI library you can use:

application/libraries/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;
  }

}

Then in your controller:

application/controllers/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 <no-reply@mg.example.com>",
      'to' => "somerandomuser@gmail.com",
      'subject' => "Welcome to Example.com",
      'text' => "We just want to say hi. Have fun at Example.com"
    ]);
  }

}

You must use a valid API key and base url for it to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!