15

I am trying to send email on codeigniter with attach file.

I always receive email successfully. However , I never receive with attach file. Below is code and highly appreciate for all comments.

    $ci = get_instance();
    $ci->load->library('email');
    $config['protocol'] = "smtp";
    $config['smtp_host'] = "ssl://smtp.gmail.com";
    $config['smtp_port'] = "465";
    $config['smtp_user'] = "test@gmail.com";
    $config['smtp_pass'] = "test";
    $config['charset'] = "utf-8";
    $config['mailtype'] = "html";
    $config['newline'] = "\r\n";

    $ci->email->initialize($config);

    $ci->email->from('test@test.com', 'Test Email');
    $list = array('test2@gmail.com');
    $ci->email->to($list);
    $this->email->reply_to('my-email@gmail.com', 'Explendid Videos');
    $ci->email->subject('This is an email test');
    $ci->email->message('It is working. Great!');

    $ci->email->attach( '/test/myfile.pdf');
    $ci->email->send();
mgphyo zaw
  • 181
  • 1
  • 2
  • 5

9 Answers9

28

$this->email->attach()

Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For multiple attachments use the function multiple times. For example:

public function setemail()
{
$email="xyz@gmail.com";
$subject="some text";
$message="some text";
$this->sendEmail($email,$subject,$message);
}
public function sendEmail($email,$subject,$message)
    {

    $config = Array(
      'protocol' => 'smtp',
      'smtp_host' => 'ssl://smtp.googlemail.com',
      'smtp_port' => 465,
      'smtp_user' => 'abc@gmail.com', 
      'smtp_pass' => 'passwrd', 
      'mailtype' => 'html',
      'charset' => 'iso-8859-1',
      'wordwrap' => TRUE
    );


          $this->load->library('email', $config);
          $this->email->set_newline("\r\n");
          $this->email->from('abc@gmail.com');
          $this->email->to($email);
          $this->email->subject($subject);
          $this->email->message($message);
            $this->email->attach('C:\Users\xyz\Desktop\images\abc.png');
          if($this->email->send())
         {
          echo 'Email send.';
         }
         else
        {
         show_error($this->email->print_debugger());
        }

    }
Nitheesh K P
  • 1,090
  • 8
  • 17
  • Could you please help me figure out what I might have done wrong here http://stackoverflow.com/questions/43676702/send-mail-with-codeignitor-email-libray. Thanks – G B Apr 28 '17 at 10:25
  • I have found the article which describe how to send emails in a CodeIgniter application using SMTP. Using the well known and maintained email sending class.https://www.cloudways.com/blog/send-email-codeigniter-smtp/ – Owais Alam Aug 23 '17 at 11:48
  • How would you attach a file dynamically? What I meant is if I want to attach different files at different instance, how would you do that? – julie Feb 09 '18 at 05:04
  • You need to fetch file name from database everytime @julie – Bergin Oct 25 '18 at 05:33
  • @nitheesh-k-p Hello!, where one should have that file, i mean which secured path?, i dont want people to guess the file name and then download it from assets folder – gepex Nov 26 '20 at 01:43
5

i have this problem before , the problem with the path file , so i change the path file to


$attched_file= $_SERVER["DOCUMENT_ROOT"]."/uploads/".$file_name; $this->email->attach($attched_file);


And it works fine with me

Ahmed Bermawy
  • 2,290
  • 4
  • 35
  • 42
3

With Codeigniter 3.1.0 I had same problem. Seems that there is missing a "\r\n":

Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>

should be:

Content-Type: application/pdf; name="test.pdf"<br>
Content-Disposition: attachment;<br>
Content-Transfer-Encoding: base64<br>
<br>
JVBERi0xLjYNJeLjz9MNCjQzNyAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3OTUyMTYvTyA0Mzkv<br>
RSA2ODEwODcvTiA0L1QgNzk0ODA3L0ggWyA1NjQgMjYxXT4+DWVuZG9iag0gICAgICAgICAgICAg<br>

I changed line 725 in system/libraries/Email from

 'content'       => chunk_split(base64_encode($file_content)),<br>

to

'content'       => "\r\n" . chunk_split(base64_encode($file_content)),<br>

It works for me, but not the perfect fix.

BWA
  • 5,672
  • 7
  • 34
  • 45
  • Thank you so much, I was digging around for the solution of an email attachment sent out file with gmail but not with other mail client. I know it must be something small like this. CI must get it fixed at some stage. – Mike C Dec 26 '16 at 06:16
2

Try putting the full path in $ci->email->attach();

On windows this would like something like

$ci->email->attach('d:/www/website/test/myfile.pdf');

This method has worked well for me in the past.

dangermark
  • 544
  • 2
  • 5
  • 17
1

If you want to send attachment in email Without uploading file on server, please refer below.

HTML View file

echo form_input(array('type'=>'file','name'=>'attach_file','id'=>'attach_file','accept'=>'.pdf,.jpg,.jpeg,.png'));

Controller file

echo '<pre>'; print_r($_FILES); shows below uploaded data.

[attach_file] => Array
(
    [name] => my_attachment_file.png
    [type] => image/png
    [tmp_name] => C:\wamp64\tmp\php3NOM.tmp
    [error] => 0
    [size] => 120853
)

We will use temporary upload path [tmp_name] where attachment is uploaded, because we DO NOT want to upload attachment file on server.

$this->email->clear(TRUE); //any attachments in loop will be cleared.
$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.');
//Check if there is an attachment
if ( $_FILES['attach_file']['name']!='' && $_FILES['attach_file']['size'] > 0 )
{
    $attach_path = $_FILES['attach_file']['tmp_name'];
    $attach_name = $_FILES['attach_file']['name'];
    $this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();
G_real
  • 1,137
  • 1
  • 18
  • 28
0

use path helper

$this->load->helper('path');
$path = set_realpath('./images/');

on email line

$this->email->attach($path . $your_file);
topimiring
  • 140
  • 1
  • 8
0

here i am using phpmailer to send mail
here full code is mention below

$this->load->library('My_phpmailer');
                $mail = new PHPMailer();
                $mailBody = "test mail comes here2";
                $body = $mailBody;
                $mail->IsSMTP(); // telling the class to use SMTP
                $mail->Host = "ssl://smtp.gmail.com"; // SMTP server
                $mail->SMTPDebug = 1;// enables SMTP debug information (for testing)
                // 1 = errors and messages
                // 2 = messages only
                $mail->SMTPAuth = true;// enable SMTP authentication
                $mail->Host = "ssl://smtp.gmail.com"; // sets the SMTP server
                $mail->Port = 465;// set the SMTP port for the GMAIL server
                $mail->Username = "YourAccountIdComesHere@gmail.com"; // SMTP account username
                $mail->Password = "PasswordComesHere";// SMTP account password
                $mail->SetFrom('SetFromId@gmail.com', 'From Name Here');
                $mail->AddReplyTo("SetReplyTo@gmail.com", "Reply To Name Here");
                $mail->Subject = "Mail send by php mailer";
                $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                $mail->MsgHTML($body);
                $mail->AddAttachment($cdnStorage . '/' . $fileName);
                $address ='WhomeToSendMailId@gmail.com';
                $mail->AddAddress($address, "John Doe");
                if (!$mail->Send()) {
                    echo "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    echo "Message sent!";
                }
Amit Joshi
  • 456
  • 1
  • 8
  • 21
0

Here Is Full Source Code

    $validation_rules = array(
        array('field' => 'name', 'rules' => COMMON_RULES),
        array('field' => 'email', 'rules' => COMMON_RULES),
        array('field' => 'message', 'rules' => COMMON_RULES),
    );

    $this->validation_errors($validation_rules);

    $name = $this->input->post('name');
    $email = $this->input->post('email');
    $message = $this->input->post('message');

    $this->load->library('email');

    //upload file
    $attachment_file = "";
    if (!empty($_FILES) && isset($_FILES["attachment_file"])) {

        $image_name = $_FILES["attachment_file"]['name'];

        $ext = pathinfo($image_name, PATHINFO_EXTENSION);

        $new_name = time() . '_' . $this->get_random_string();

        $config['file_name'] = $new_name . $ext;
        $config['upload_path'] = "uploads/email/";
        $config['allowed_types'] = "*";

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if ($this->upload->do_upload('attachment_file')) {

            $finfo = $this->upload->data();
            $attachment_file = base_url() . 'uploads/email/' . $finfo['file_name'];
        } else {

            $error = $this->upload->display_errors();
            $this->msg = $error;
            $this->_sendResponse(5);
        }
    }

    $this->email->from($email, "$name")
            ->to("example@gmail.com")
            ->subject("FeedBack From $name")
            ->message($message)
            ->attach($attachment_file);

    if ($this->email->send()) {

        // temp pass updated.
        $this->msg = "Email send successfully.";
        $this->_sendResponse(1);
    } else {

        $this->msg = "Internal server error/Something went wrong.";
        $this->_sendResponse(0);
    }
-1
 $this->load->library('email'); // Loading the email library.
 $this->email->clear(TRUE);
 $this->email->from($user_email, $name);
 $this->email->to('email@gmail.com');
 $this->email->subject("Some subject");
 $this->email->message("Some message");
 if($_FILES['userfile']['name']!='' && $_FILES['userfile'['size'] > 0){
     $attach_path = $_FILES['userfile']['tmp_name'];
     $attach_name = $_FILES['userfile']['name'];
     $this->email->attach($attach_path,'attachment',$attach_name);
}
$this->email->send();
Saddam Khan
  • 159
  • 1
  • 6