Ad Code

Ticker

6/recent/ticker-posts

How to send email with attachment in codeigniter

Send Email with attachment

How to send email with attachment in codeigniter



There is a set of configured functions for sending mails from Codeigniter with the attachment of any files, there is the $config array which includes the configuration of SMTP mail.

There are use Gmail SMTP configuration.

function sendMail()
  {
        $config=array(
          'mailpath' => '/usr/sbin/sendmail',
          'protocol'=>'smtp',
          'smtp_host'=>'ssl://smtp.gmail.com',
          'smtp_port'=>465,
          'smtp_user'=>'yourmail@gmail.com',
          'smtp_pass'=>'mailpassword',
          'mailtype'  => 'html', 
          'charset'   => 'iso-8859-1'
        );

        $this->load->library("email",$config);

        $this->email->set_newline("\r\n");
        $this->email->from('From Mail', 'From name');
        $this->email->to('user@usermail.in');
        $this->email->subject('Email Attachment Test');
        $this->email->message('Testing the attachment email class.'); 
        
        $path=$_SERVER["DOCUMENT_ROOT"];
        $file=$path."/example.csv";

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

        if($this->email->send())
        {
            echo "Mail send successfully with attachement!";
        }else{
            show_error($this->email->print_debugger());
        }
    }

There are made some changes like attachment file path:-

$path=$_SERVER["DOCUMENT_ROOT"];
$file=$path."/exam.csv";

If you are used to sending mail using Html form with file input then use the $_FILES in PHP and use temp file path for attaching in the mail function.

And also another configuration variable:-

From Mail:- this is a mail which is defined as a sender mail.
From Name:- sender name.
To('user@usermail.in'):- There is a recipient email address.
And Subject and message.

In the message section, you can also use normal text or Html files, if use send Html mail then you must use in configuration setting like this:-

'mailtype'  => 'html',

this is defined as a mail type, and this is also accepted normal text and attached files in mail.

Post a Comment

4 Comments

Ad Code