Asked  2 Years ago    Answers:  5   Viewed   240 times

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();
    $config['protocol'] = "smtp";
    $config['smtp_host'] = "ssl://";
    $config['smtp_port'] = "465";
    $config['smtp_user'] = "[email protected]";
    $config['smtp_pass'] = "test";
    $config['charset'] = "utf-8";
    $config['mailtype'] = "html";
    $config['newline'] = "rn";


    $ci->email->from('[email protected]', 'Test Email');
    $list = array('[email protected]');
    $this->email->reply_to('[email protected]', 'Explendid Videos');
    $ci->email->subject('This is an email test');
    $ci->email->message('It is working. Great!');

    $ci->email->attach( '/test/myfile.pdf');




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="[email protected]";
$subject="some text";
$message="some text";
public function sendEmail($email,$subject,$message)

    $config = Array(
      'protocol' => 'smtp',
      'smtp_host' => 'ssl://',
      'smtp_port' => 465,
      'smtp_user' => '[email protected]', 
      'smtp_pass' => 'passwrd', 
      'mailtype' => 'html',
      'charset' => 'iso-8859-1',
      'wordwrap' => TRUE

          $this->load->library('email', $config);
          $this->email->from('[email protected]');
          echo 'Email send.';

Thursday, September 1, 2022

Found this code as one of the first hits of the google://pear mail attachment search.


$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = './files/';
$hdrs = array(
              'From'    => '[email protected]',
              'To'      => '[email protected]',
              'Subject' => 'Test mime message'

$mime = new Mail_mime();



$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail =& Mail::factory('mail', $params);
$mail->send('[email protected]', $hdrs, $body); 
Saturday, October 29, 2022

Currently there is no easy way in ZF2 (2.2) to combine a multipart/alternative body (html with text alternative for clients that cannot/do-not-want-to use html) with attachments. If you add the 'multipart/alternative' content-type header to the entire message, in some email clients the attachment (link) will not be displayed.

The solution is to split the message in two, the body (text and html) and the attachment:

an example:

        $content  = new MimeMessage();
        $htmlPart = new MimePart("<html><body><p>Sorry,</p><p>I'm going to be late today!</p></body></html>");
        $htmlPart->type = 'text/html';
        $textPart = new MimePart("Sorry, I'm going to be late today!");
        $textPart->type = 'text/plain';
        $content->setParts(array($textPart, $htmlPart));

        $contentPart = new MimePart($content->generateMessage());        
        $contentPart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $content->getMime()->boundary() . '"';

        $attachment = new MimePart(fopen('/path/to/test.pdf', 'r'));
        $attachment->type = 'application/pdf';
        $attachment->encoding    = Mime::ENCODING_BASE64;
        $attachment->disposition = Mime::DISPOSITION_ATTACHMENT;

        $body = new MimeMessage();
        $body->setParts(array($contentPart, $attachment));

        $message = new Message();
        ->addTo('[email protected]')
        ->addFrom('[email protected]')
        ->setSubject('will be late')

        $transport = new SmtpTransport();
        $options   = new SmtpOptions($transportConfig),


For the above you would need the following use statements:

use ZendMailMessage;
use ZendMailTransportSmtp as SmtpTransport;
use ZendMailTransportSmtpOptions;
use ZendMimeMime;
use ZendMimePart as MimePart;
use ZendMimeMessage as MimeMessage;

ZF1 had a _buildBody() method in Zend_Mail_Transport_Abstract which did this automatically.

Tuesday, November 29, 2022

$sender_lname = filter_var($_POST["fname"], FILTER_SANITIZE_STRING); Should be, $sender_lname = filter_var($_POST["lname"], FILTER_SANITIZE_STRING);

If you are refreshing a browser, they tend to cache the last POST request. You may be asked if you want to re-submit form data. Try adding a hidden field with a hash value for a token.

<input type="hidden" name="token" value="someHashValue">

Implement sessions to compare the submitted token against the one stored in $_SESSION.

session_regenerate_id(); //Used properly, helps deter session fixation;
$_SESSION['token'] = "someHashValue"; //Must be unique for each page load.

Use a good hashing function to create the token. I would steer clear of md5 and sha1.


if($_SESSION['token'] === $_POST['token'])
    //Good. You want to filter, validate, and check this early on.
    //Whatever you do, just be consistent.

Also, be wary of using the file name ($file_name = $_FILES['file_upload']['name'];) supplied by the browser in your code. Most would say find a way not to use it, but if you do, you still need to filter and validate it in some way. Re-naming the file might be appropriate. Checking the file size is a good idea, too. Don't rely too heavily on the php.ini on the file size bit. If file type matters, you can even try to inspect the file before accepting it.

Lastly, when you get there, if you are going to use PHP filter functions, it may be a good idea to use filter_input_array() with INPUT_POST for your POST data. For the $_FILES superglobal, I made a separate routine just for validating it (but, you cannot use filter_input_array() for that). Good luck! You are on your way!

Tuesday, December 6, 2022

Explicitly filling in the ContentDisposition fields did the trick.

if (attachmentFilename != null)
    Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
    ContentDisposition disposition = attachment.ContentDisposition;
    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
    disposition.FileName = Path.GetFileName(attachmentFilename);
    disposition.Size = new FileInfo(attachmentFilename).Length;
    disposition.DispositionType = DispositionTypeNames.Attachment;

BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!

smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Monday, November 14, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages