CodeIgniter教程:发送邮件
用CodeIgniter发送电子邮件很容易。您还可以在CodeIgniter中配置有关电子邮件的选项。CodeIgniter为发送电子邮件提供了以下功能。
支持多协议:Mail, Sendmail和SMTP
面向SMTP的TLS和SSL加密
多个收件人
CC和BCCs
HTML或纯文本电子邮件
支持附件
自动换行
邮件优先级
密件抄送批处理模式,允许将大型电子邮件列表分成小批量密件抄送。
电子邮件调试工具
电子邮件类包含以下方法来简化发送电子邮件的工作。
from($from[, $name = ''[, $return_path = NULL]]):参数$from代表发送方邮件地址,$name为发送方名字,$return_path为可选将未送达的邮件重定向到指定邮件地址。
reply_to($replyto[, $name = '']):参数 $replyto为回复的邮件地址 $name为回复邮件地址的显示名称
to($to) :参数 $to为逗号分隔的邮件地址,也可以传递数组。
cc($cc) :参数 $cc为逗号分隔的邮件地址,也可以传递数组。
subject($subject) :参数subject为邮件主题。
message($body) :参数 $body为邮件内容。
set_alt_message($str): 参数$str为备选电子邮件正文。
set_header($header, $value):参数$header为邮件头的键,$value为邮件头的值。
clear([$clear_attachments = FALSE]):参数$clear_attachments为是否清除附件。
send([$auto_clear = TRUE]):参数$auto_clear代表是否自动清除消息数据。
attach($filename[, $disposition = ''[, $newname = NULL[, $mime = '']]]):参数$filename代表文件名,$disposition (string):附件的“配置”,$newname 邮件中使用的自定义文件名,$mime要使用的MIME类型。
attachment_cid($filename):参数$filename为现有附件文件名
发送邮件
要使用CodeIgniter发送邮件,首先需要加载email库。
$this->load->library('email');加载email库之后,只需执行以下功能来设置发送邮件所需的元素。from()函数用于设置邮件的发送方,to()函数用于设置邮件的发送方,subject()和message()函数用于设置邮件的主题和消息。
$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');执行的send()函数来发送邮件。
$this->email->send();
例子
创建一个控制器文件并保存在application/controller/Email_controller.php中
<?php
class Email_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
}
public function index() {
$this->load->helper('form');
$this->load->view('email_form');
}
public function send_mail() {
$from_email = "your@example.com";
$to_email = $this->input->post('email');
//Load email library
$this->load->library('email');
$this->email->from($from_email, 'Your Name');
$this->email->to($to_email);
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
//Send mail
if($this->email->send())
$this->session->set_flashdata("email_sent","Email sent successfully.");
else
$this->session->set_flashdata("email_sent","Error in sending Email.");
$this->load->view('email_form');
}
}
?>创建一个名为email_form.php的视图文件,并保存在application/views/email_form.php。
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Email Example</title>
</head>
<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Email_controller/send_mail');
?>
<input type = "email" name = "email" required />
<input type = "submit" value = "SEND MAIL">
<?php
echo form_close();
?>
</body>
</html>在application/config/routes.php的routes.php文件中进行更改,在文件末尾添加以下行。
$route['email'] = 'Email_Controller';
通过访问以下链接执行上述示例。用你自己网站的网址替换yoursite.com。
http://yoursite.com/index.php/email