用户
 找回密码
 入住 CI 中国社区
搜索
查看: 3906|回复: 3
收起左侧

[版本 3.x] 使用CI Mail类发送邮件实例 (QQ , mailgun)

[复制链接]
发表于 2014-12-29 13:59:08 | 显示全部楼层 |阅读模式
本帖最后由 Closer 于 2014-12-29 14:24 编辑

代码已经应用在实际项目中,邮箱用的是QQ的企业邮箱,实测mailgun也可以使用,其他邮箱没有测试过。
相关代码如下:
首先重写CI_Email(./application/libraries/MY_Email.php):
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
PHP复制代码
 
<?php  if ( ! 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复制代码
 
<?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 */
 
 
复制代码


评分

参与人数 1威望 +15 收起 理由
Closer + 15 赞一个!

查看全部评分

发表于 2014-12-29 14:14:12 | 显示全部楼层
感謝您的分享!

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

 
发表于 2015-1-5 08:47:24 | 显示全部楼层
楼主都已经开始用3.0开发了,不错,学习了
 楼主| 发表于 2015-1-5 10:24:52 | 显示全部楼层
bob 发表于 2015-1-5 08:47
楼主都已经开始用3.0开发了,不错,学习了

3.0已经接近release了,相对比较稳定,不会有大的改动,没有比较大的feature了;
等正式release,替换一下system文件夹就行了

本版积分规则