Code Igniter -> attach email

How do you use the email->attach function?

I can’t figure what is happen, cos when i put the code for email->attach the mesage came in blank(the mail body) and there is no attach.

If i remove that code line, everything come back to normal..

thank you

my controller (sendmail.php)

<?php

 class Sendmail extends Controller {

      function __construct() {
           parent::Controller();
           $this->load->library('email');
           $this->load->helper('url');
           $this->load->helper('form');
           $this->load->library('validation');
      }

      function index() {

           $info = array (
                'nome'  => $this->input->post('nome'),
                'mail'  => $this->input->post('email'),
                'motivo'    => $this->input->post('motivo'),
                'mensagem'  => $this->input->post('mensagem'),
                'anexo' => $this->input->post('upload'),
           );

           $this->load->library('email');
           $this->email->set_newline('\r\n');

           $this->email->clear();
           $this->email->from($info['mail'], $info['nome']);
           $this->email->to('[email protected]');
     /* $this->email->cc(''); # não é preciso */
           $this->email->subject($info['motivo']);
           $this->email->message($info['mensagem']);
           $this->email->attach($info['anexo']);

           if ($this->email->send() ) {
                echo 'sent';
           }

           else {
            $this->load->view('formulario');
    # show_error( $this->email->print_debugger() );
           }

      }

 }
?>

my view (formulario.php)

    <?php
    echo form_open_multipart('davidslv/index.php/sendmail');
?>
          <label for="nome">nome</label>
          <input type="text" name="nome" id="nome" required />

          <label for="email">email</label>
          <input type="text" name="email" id="email" required />

          <label for="assunto">assunto</label>
          <select name="motivo">
               <option value="motivo1">motivo1</option>
               <option value="motivo2">motivo2</option>
               <option value="motivo3">motivo3</option>
          </select>

          <p> <label for="mensagem">mensagem</label>
          <textarea name="mensagem" id="mensagem" rows="8" cols="30" required></textarea>
          </p>

          <label for="upload">documento</label>
          <input type="file" id="upload" name="upload" size="18"/>
          <input type="submit" id="enviar" name="enviar" value="Enviar!" />

     </form>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library: $this->upload->do_upload() to your server into some directory. the upload library needs to be configured, which file types are allowed etc. if the upload was successful, the do_upload function returns extensive data about where the file is stored. you can use the ‘full_path’ index from the array to attach this file to the email. then send the mail. after that you may delete the file from your server. Here are some code fragments that might help.

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

if($_FILES['upload']['size'] > 0) { // upload is the name of the file field in the form

$aConfig['upload_path']      = '/someUploadDir/';
$aConfig['allowed_types']    = 'doc|docx|pdf|jpg|png';
$aConfig['max_size']     = '3000';
$aConfig['max_width']        = '1280';
$aConfig['max_height']       = '1024';

$this->upload->initialize($aConfig);

  if($this->upload->do_upload('upload'))
  {
    $ret = $this->upload->data();
  } else {
    ...
  }

  $pathToUploadedFile = $ret['full_path'];
  $this->email->attach($pathToUploadedFile);
  ...
  $this->email->send();
  ...
}
...

Hope this helped…

Solution 2

$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:

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

$this->email->send();

Codeigniter Email Class

Solution 3

This is Absolutely right code Please Try

$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
$config['max_size']         = '9000';
$config['encrypt_name']     = true;

$image_data = $this->upload->data();
$fname=$image_data[file_name];
$fpath=$image_data[file_path].$fname;

$this->email->attach($fpath);

Solution 4

step 1:You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library:

$this->upload->do_upload() to your server into some directory.

step 2:

 $file=upload file;


 $file_path='uploaded directory on your server(eg:uploads/career)'.$file;

step 3:just include

$this->email->attach($file_path);
$this->email->send();

Solution 5

This is a late update, but it might be useful.
It was said twice

“You can not directly attach a file from the upload field of your form
to an email”

. However, this works fine in Codeigniter 3.0

foreach ($_FILES as $key => $file)
{
    if ($file['error'] == 0)
    {
        $this->email->attach($file['tmp_name'], '', $file['name']);
    }
}

(Though, the email is not sent and no errors are shown, if there are two files with the same name)

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply