CodeIgniter - 邮件发送

CodeIgniter - 邮件发送 首页 / Codeigniter入门教程 / CodeIgniter - 邮件发送

使用CodeIgniter发送电子邮件要容易得多。您还可以在CodeIgniter中配置有关电子邮件的首选项。

发送邮件

要使用CodeIgniter发送电子邮件,首先必须使用以下命令加载电子邮件库-

$this->load->library('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();

完整示例

创建一个控制器文件 Email_controller.php 并将其保存在 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'); 
   
         //加载 email 库 
         $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.'); 
   
         //发送邮件
         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';

通过访问以下链接执行以上示例。用您网站的URL替换yoursite.com。

http://yoursite.com/index.php/email

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

机器学习40讲 -〔王天一〕

深入剖析Kubernetes -〔张磊〕

Android开发高手课 -〔张绍文〕

说透敏捷 -〔宋宁〕

技术管理案例课 -〔许健〕

技术面试官识人手册 -〔熊燚(四火)〕

结构写作力 -〔李忠秋〕

结构会议力 -〔李忠秋〕

云时代的JVM原理与实战 -〔康杨〕

好记忆不如烂笔头。留下您的足迹吧 :)