Search code examples
codeigniteremail-attachments

Attach a file to an email in codeigniter


This is my code and I want to attach multiple files to the email. This code is working and sending the email, but I cannot attach an attachment to the email. Email title and the message are user inputs and the sending email address is also a user input.In here I used check boxes to select the email addresses that sending the email.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sendemail extends CI_Controller {

  public function __construct()
  {
    /*call CodeIgniter's default Constructor*/
    parent::__construct();
    /*load database libray manually*/
    $this->load->database();
    $this->load->library('session');
    /*load Model*/
    $this->load->helper('url');
    
  }

   public function index() { 
      $this->load->view('Admin/dashboard'); 
   } 


  public function form_validation()  
      {  
           //echo 'OK';  
           $this->load->library('form_validation');  
           $this->form_validation->set_rules("title", "title", 'required');  
           $this->form_validation->set_rules("files[]", "files[]");  
           $this->form_validation->set_rules("message", "message", 'required');  
           $this->form_validation->set_rules("single_select[]", "single_select[]", 'required');  
           if ($this->form_validation->run()){

            if(isset($_POST['submit'])){ 
              $checkbox1=$_POST['single_select'];
                  foreach($checkbox1 as $chk1){ 
                      
                   
                    $this->load->library('email');
                    $this->email->to($chk1);
                    $this->email->from('xxxxxxxxxx@gmail.com');
                    $this->email->subject($this->input->post("title"));
                    $this->email->message($this->input->post("message"));
                    
                    $this->email->send();

                    
                }
                $this->session->set_flashdata('message','Email sent.');
                redirect('Admin/index');
            }
            else{
              $this->session->set_flashdata('message','Something went wrong!');
              redirect('Admin/index');
            }
        }

        else{
          $this->session->set_flashdata('message','Something went wrong!');
          redirect('Admin/index');
        }     
    } 
}```


Solution

  • You can attach multiple files like this

    $this->email->attach('/path/to/photo1.jpg');
    $this->email->attach('/path/to/photo2.jpg');
    $this->email->attach('/path/to/photo3.jpg');