在 Codeigniter 的类库参考中封装好了 Email 类,使用时只需要载入调用即可.
我简单封装了一个发送 email 的方法 custom_mail_smtp,代码如下
/**
* smtp 发送邮件
*/
if (!function_exists("custom_mail_smtp")){
function custom_mail_smtp($type=1,$from=[],$to,$subject,$message,$attach=null,$cc=null,$bcc=null){
$CI = get_instance();
$CI->load->library("email");
switch ($type){
case 1: // text
$config['mailtype'] = 'text';
break;
case 2: // html
$config['mailtype'] = 'html';
break;
default:
}
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.163.com';
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'xxx';
$config['smtp_port'] = '25';
$config['wordwrap'] = false;
$CI->email->initialize($config);
$CI->email->from($from['from_email'],$from['from_name']);
$CI->email->to($to);
if (!empty($cc)){
$CI->email->cc($cc);
}
if (!empty($bcc)){
$CI->email->bcc($bcc);
}
if (!empty($attach)){
$CI->email->attach($attach);
}
// $CI->email->attach('http://img2.imgtn.bdimg.com/it/u=875342312,3557917522&fm=26&gp=0.jpg');
// $CI->email->attach('./uploads/timg.jpg');
$CI->email->subject($subject);
$CI->email->message($message);
return $CI->email->send();
//debugger
// $CI->email->send(false);
// echo $CI->email->print_debugger();
}
}
「参考」网上还有一种 config 的配置方式是这样的
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.163.com';
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'xxx';
$config['smtp_port'] = '465';
$config['wordwrap'] = false;
这里把 smtphost 前加了 ssl://, smtp_port 改成了 465,这两种配置方式都是可以的.
我们在控制器中直接调用
/**
* email 类
*/
public function test13(){
$this->load->helper("MY_custom_functions");
$email_html = $this->load->view("email_html","",true);
$rs = custom_mail_smtp(2,
[ "from_email" => "[email protected]", "from_name" => "小彬" ],
"[email protected]","嘤嘤,你好呀~",$email_html,"./uploads/timg.jpg");
var_dump($rs);
}
以上邮件就可以正常发送了
对于添加附件的说明:
1 . 对于文档上说的附件可以使用 URL 的格式,我试了各种方法,都没有成功,知道如何实现的大神谢谢告诉我一下怎么实现.
2 . attach() 方法的第一个参数是相对于入口文件 index.php 的文件路径,比如我的例子中
我的附件图片 timg.jpg 相对于入口文件 index.php 的路径就是 "./uploads/timg.jpg", "./" 表示项目根目录.