wlyx 发表于 2014-12-29 13:59:08

使用CI Mail类发送邮件实例 (QQ , mailgun)

本帖最后由 Closer 于 2014-12-29 14:24 编辑

代码已经应用在实际项目中,邮箱用的是QQ的企业邮箱,实测mailgun也可以使用,其他邮箱没有测试过。
相关代码如下:
首先重写CI_Email(./application/libraries/MY_Email.php):

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

/**
* MY_Email.php Class
*
* Extends CodeIgniter Controller
*
*/

class MY_Email extends CI_Email{

    var $send_from = Null;
    var $send_user = Null;

    public function __construct($config = array())
    {
      parent::__construct($config);

      $this->send_from = $this->smtp_user;
      $this->send_user = 'noreply';//此项可从配置文件里读取
    }

    public function subject($subject)
    {
      $subject = '=?'.$this->charset.'?B?'.base64_encode($subject).'?=';
      $this->set_header('Subject', $subject);
      return $this;
    }

    public function sendMail($to,$subject,$message,$attach=NULL){

      $this->from($this->smtp_user,$this->send_user);
      $this->to($to);
      $this->subject($subject);
      $this->message($message);
      if(!empty($attach))
      {
            $this->attach($attach);
      }
      return $this->send();
    }
}

/* End of file MY_Email.php */
/* Location: ./application/libraries/MY_Email.php */


创建配置文件./application/config/email.php

<?phpif ( ! defined('BASEPATH')) exit('No direct script access allowed');

//---------------------------------------------------

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.exmail.qq.com';
$config['smtp_user'] = 'noreply@*****.com';
$config['smtp_pass'] = '******';
$config['mailtype'] = 'html';
$config['validate'] = TRUE;
$config['newline'] = "\r\n";
$config['crlf'] = "\r\n";


/* End of file email.php */
/* Location: ./application/config/email.php */





然后就可以在controller里调用了 /application/controllers/Cron.php

<?php

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

//---------------------------------------------------

class Cron extends CI_Controller{

    public function __construct()
    {
      parent::__construct();
      $this->load->library('email');
    }

    public function index()
    {
      $to="****@qq.com";
      $subject="Email test";
      $message="Testing the email class";

         $this->email->sendMail($to,$subject,$message);
    }


}


/* End of file Cron.php */
/* Location: ./application/controllers/Cron.php */



Closer 发表于 2014-12-29 14:14:12

感謝您的分享!

因為我自己本身沒有 QQ
所以歡迎有 QQ 的開發者幫忙測試
萬分感謝!

 

bob 发表于 2015-1-5 08:47:24

楼主都已经开始用3.0开发了,不错,学习了

wlyx 发表于 2015-1-5 10:24:52

bob 发表于 2015-1-5 08:47
楼主都已经开始用3.0开发了,不错,学习了

3.0已经接近release了,相对比较稳定,不会有大的改动,没有比较大的feature了;
等正式release,替换一下system文件夹就行了
页: [1]
查看完整版本: 使用CI Mail类发送邮件实例 (QQ , mailgun)