codeigniter 傳送郵件
阿新 • • 發佈:2018-11-05
在 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", "./" 表示專案根目錄.