我正在使用CodeIgniter,我正在使用Mailgun API发送电子邮件。但是我在回复curl_exe()时收到FORBIDDEN,如代码所示:
<?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;
}
}
?>
我搜索了它也搜索了SO也没有得到解决方案。请帮我这个。 此外,还没有发送电子邮件。
答案 0 :(得分: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 <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"
]);
}
}
您必须使用有效的API密钥和基本网址才能正常工作。