×

CodeIgniter Email Class

CodeIgniter provides an e-mail library that helps to send a message from one application to another. You can create and send text messages easily in CodeIgniter application even you can set email preferences as per needs.

An email class contains the following features:

  • It supports Multiple Protocols such as TLS, Mail, Send mail and SMTP (Simple Mail Transfer Protocol)
  • TLS and SSL Encryption
  • Multiple recipients
  • CC and BCCs
  • HTML or plaintext email
  • Attachments
  • Word wrapping
  • Priorities
  • BCC Batch Mode, it permits to broke large email lists into sub BCC batches.
  • Email Debugging tools

Load an Email Class

Before using the email class in Codeigniter, you must load in the controller file by following the

Syntax:

$this -> load-> library ( ‘email’ );

Various function of email class that helps to send an email

  1. from(): As we know, the from () function indicates the personal ID of the user who is sending an email to another person via email.

Syntax

from($from [, $name =’’ [, $return_path = null ] ]);

It has three parameters:

$from (string): It denotes the user email address.

$name: It is an optional parameter. If you want to display your name in an email, you can pass the name in this field.

$return_path (string): In this parameter, you can set an alternate email address to redirect the mail.

  • reply_to(): As the name suggests, it helps to reply to a mail by defining an email address to the relpy_to() function.

Syntax

reply_to( $reply_to [, $name = ‘’] );

It has two parameters:

$reply_to: It defines an email address to reply the same user.

$name: It displays the username along with the email address.

  • to(): The to() function indicates the name of the recipient email address. And if you want to send a message to more than one user, then you need to define all the email in to() function.

Syntax

to($to);

$to: It defines the email address of the recepint. You can also pass multiple email addresses by using a comma-delimited list or an array.

  • cc(): The cc() function is used to send carbon copies of the mail to other people, besides the main recipients.

Syntax

cc ($cc);

$cc: It contains the recipients’ email addresses, and if you want to share email more than one person, you can add the multiple email addresses separated by comma-delimiter or an array.

  • bcc(): A bcc standsfor Blind Carbon Copy. It is different from cc() and to() function, as in this function the main recipient couldn't know about the bcc recipients.

Syntax

bcc ($bcc);

$bcc: It takes an email address for creating a blind carbon copy.

  • subject(): As the name defines, a subject() function is used to set the purpose of an email.

Syntax

subject( $subject):

$subject: It is used as a variable for defining the subject of an email.

  • message(): It is like the message body of an email in which the sender or receiver writes the messages.

Syntax

message($body);

$body: It provides an area to write the content or message that you want to share with another person.

  • set_alt_message(): As the name suggests, a set_alt_message() function is an optional message string that is used to send an alternate email text when the receiver does not receive the particular message.

Syntax

set_alt_message($str);

$str: In this field, you can pass an alternative string.

  • set_header(): A set_header() function is used to set headers in emails. It also allows adding more than one header to an email.

Syntax

set_header($header, $value);

It contains two parameters:

$header:  It defines the header name of an email.

$value: It contains the header value of an email.

  1. clear(): As the function defines, it is used to clear all attached documents that are used to send an email in a loop.

Syntax

clear( [ $clear_attachements = FALSE ]);

$clear_attachements: It uses a Boolean value that indicates whether you want to delete the attachment.

11. send(): As the name suggests, a send () function is an email sending method that returns a true or false value based on the success or failure of the email.

Syntax

send ([ $auto_clear = TRUE ]);

$auto_clear: It uses a Boolean value to automatically clear sent messages.

12. attach(): The attach () function is used to attach JPEG, PDF, text, etc. to an email while sending any type of document to an individual.

Syntax

attach ($fiilename [, $disposition = ‘’ [, $newname = null [, $mime = ‘’ ] ] ] );

It has four parameters:

$filename: It defines the filename that you want to attached to an email.

$disposition: It defines the disposition of an attachment.

$newname: It allows to add a custom filename when sending an email.

$mime: It defines the type of file that you want to attach to the email.

13. print_debugger(): It is a function that is used to show an error message when an email is not sent to the recipients’ address.

Syntax

print_debugger( [$include = array(‘headers’, ‘subject’, ‘body’) ]);

$include: It defines the part of the message that you want to display in the email.

Create an email system using Email class

Create a controller file Send_mail.php and save it in application/controller/Send_mail.php. After that, write the following program in the controller file.

Send_mail.php

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Send_mail extends CI_Controller {
             public function index()
     { 
   $this->load->helper('html');
         $this->load->helper('form');
         $this->load->view('sent2');
     }
     public function send()
 {   
   $this->load->helper('html');
 $this->load->library(‘email’);
 $this->load->library(‘config’);
     $to =  $this->input->post('from');  // It takes the recipient email address
     $cc =  $this->input->post('cname');  // It also takes the recipient email
     $bcc =  $this->input->post('bname');  // it takes an email for using bcc()
     $subject = $this->input->post('subname'); 
     $from = 'abc@example.com’;     // Here you have to pass own email id 
     $mailContent = '<!DOCTYPE><html><head></head>
     <body><table width="100%" style="border:200px; border-spacing:0;">
     <tr><td style= "background-color:red; height:50px" padding-left:5%>
     </tr>
     <tr><td style= "background-color:white; height: 50px"  padding-left:5%>
     </tr>
     <tr><td style= "background-color:green; height:50px"  padding-left:5%>
     </tr>'; 
     $mailContent .= $this->input->post('message');  /* It takes text messages from html form with the use of post method */
     $mailContent .='<tr><td style="height:20px"></td></tr>';
     $mailContent .= "<tr><td style= 'background:blue;color: green;
     padding: 5%;text-align: center;font-size: 30px;'><p style='margin-top:10px;'>
     <a href='http://tutorialandexample.com/' target='_blank' style='text-decoration:none;
     color: red;'>www.tutorialandexample.com</a></p></td></tr></table></fieldset></body></html>";
     $config['protocol']    = 'smtp'; // tls
     $config['smtp_host']    = 'ssl://smtp.gmail.com';
     $config['smtp_port']    = '465';  // gmail smtp port no.
     $config['smtp_timeout'] = '60';
     $config['smtp_user']    = 'abc@example.com;    // Your Gmail address
     $config['smtp_pass']    = 'password;  // Your Gmail password
     $config['charset']    = 'utf-8';
     $config['newline']    = "\r\n";
     $config['mailtype'] = 'html'; // or text
     $config['validation'] = TRUE; // it defines the boolean value to validate an email
     $this->email->initialize($config);
     $this->email->set_mailtype("html");
     $this->email->from($from);
     $this->email->to($to);
     $this->email->cc($cc);
     $this->email->bcc($bcc);
     $this->email->subject($subject);
     $this->email->message($mailContent);
     $this->email->attach('images/download.jpg'); // it defines an attached image
     $this->email->attach('images/mysong.mp3');
     $this->email->attach('images/jiphy.webp');
     $this->email->attach('images/illegal.mp3');
     $this->email->attach('images/valley.jpg');
     $this->email->send();
     $this->load->view('sent3'); // it calls view file
     $this->session->set_flashdata('msg', "E-Mail has been sent ");
     $this->session->set_flashdata('msg_class', 'alert-success');
 }
 }
 ?> 

Create a sent2.php view file and save it into an application/views/. After that, write the following program in the controller file.

Sent2.php

<html>
 <head>
 <title> Email sending </title>
 <h2>Send an email using SMTP </h2></br>
   <?php if($error = $this->session->flashdata('msg')){ ?>
        <p style="color: green;"><strong>Success!</strong> <?php echo  $error; ?><p>
   <?php } ?>
 </head>
   </body>
 <form action="<?php echo site_url();?>/Send_mail/send" method="post">
 <table border="2px">
 <tr style= 'color:blue'>
 <td><label for="from"><b>To:</b></label></td>
   <td><input type="email" name="from"  placeholder="Enter Email" required style= "width:100%";></td>
   </tr>
   <tr>
    <td><label for="cname"><b>CC:</b></label></td>
    <td ><input name="cname" placeholder="Enter Email" style= "width:100%";><br></td>
    </tr> 
    <tr>     
    <td><label for="bname""><b>Bcc:</b></label></td> 
    <td ><input type="email" name="bname" placeholder="Enter Email" style= "width:100%";></td>
    </tr>
    <tr>
    <td><label for="subname"><b>Subject:</b></label></td>
    <td ><textarea name="subname" rows ="2" required style= "width:100%";></textarea></td>
    </tr>
    <tr><td colspan ="2"><textarea name="message" rows ="5" 
     placeholder="Enter message here" required style= "width:100%";></textarea></td>
    </tr>
    <tr><td><label for="fileshare"><b>Attach File:</b></label></td>
    <td ><input type= "file" name="fileshare" 
     placeholder="attached document here" style= "width:100%";>
             </td>
    </tr>
    <tr>
    <td colspan="2">
    <button type="submit" class="btn btn-primary" style= "width:100%";>Send Message</button> </td></tr>
 </table>
 </form>
 </body> 
 </html> 

Create a sent3.php view file and save it into an application/views/. After that, write the following program in the controller file.

Sent3.php

 
<h3> Email has been sent successfully</h3>

Before executing the program, you have to follow these instructions, such as:

1. You have to log in with your Gmail id and click on the (six dotted) top right corner of the Gmail, it shows a pop-up box and then clicks on the account option, it shows a below screen in your system.

2. And, click on the Security option of the Gmail account and then scroll the page, it shows the below screen.

Email Class

3. After that, click on the Turn on access (not recommended) link; it redirects you to the next page, as shown in the below image.

Email Class

Now execute the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/Send_mail; it shows the output, as shown below.

Email Class

After filling the email details such as email id, subject, and message, and then click on the Send Message button, it shows the output as shown below:


Related Topics

Insert data to the database CodeIgniter

After successfully creating a database connection with the CodeIgniter application, we will now understand how we can insert records into the database. To insert a record into a database table, Codeigniter provides...

8 minutes read.

CodeIgniter ZIP Encoding Class

ZIP Encoding Class The CodeIgniter provides a Zip encoding class that are used to compress a large file into a Zip archives. And this archives files can be downloaded either to your desktop or...

5 minutes read.

How to remove an index.php file from the Codeigniter URLs?

As we know, a URL in CodeIgniter is designed in such a way that it would be search engine and human friendly, too, rather than using a standard approach to create a...

2 minutes read.

CodeIgniter URL Helper

The helper file contains some predefined functions that are used to work with URL, such as generate the current file path, transfer control, redirect, create a link, etc. Load the URL Helper Before using...

7 minutes read.

CodeIgniter Libraries

The library is an important part of the CodeIgniter framework. It has a large collection of libraries files that are used to increase the performance of an application. By default, all CodeIgniter libraries...

4 minutes read.

CodeIgniter Views

A View is a presentational part which shows the information to the users. It is a complex web page which contains navbar, header, footer, sidebar, etc. A view file cannot be called directly...

5 minutes read.

CodeIgniter Input Class

Input Class The CodeIgniter framework provides an input class that includes various input functions to pre-process global input data for protection; furthermore, it also provides some helper functions to obtain input data. This...

11 minutes read.

CodeIgniter Inflector Helper

The inflector helper file contains some predefined function that allows users to change their English words into plural, singular, and camel case, etc. Loading an Inflector Helper Before using an inflector helper function, you must...

3 minutes read.

Installation of CodeIgniter

Before installing CodeIgniter, you need to make sure that the wamp or xampp server in the system is preinstalled. The installation procedure for CodeIgniter is very easy. You can download CodeIgniter by following these...

2 minutes read.

CodeIgniter Form Helper

A form helper file contains different functions that works with forms. It is used to create various functionality in a form such as dropdown, radio button, password, upload, hidden data, etc. These functionalities...

12 minutes read.

CodeIgniter Creating Library

As we know, CodeIgniter has a large collection of library functions that are stored in the system/libraries folder. CodeIgniter also provides some additional functionality in library files. For example, if you want to...

3 minutes read.

CodeIgniter User Agent Class

User Agent Class The CodeIgniter provides a user agent class that helps to identify and collect information about the browser, mobile devices, or robots visiting your site. Besides this, it is also used...

4 minutes read.

CodeIgniter Encrypt Class

The Codeigniter provides an encrypt class used to protect confidential data stored on computer systems or data transmitted over a network. It provides two-way data encryption techniques such as Mcrypt PHP extension and...

4 minutes read.

Calendaring Class CodeIgniter

Calendaring Class The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar...

6 minutes read.

CodeIgniter File Helper

The file helper function is used to perform various tasks with files such as accessing files, writing data to files, deleting files, and more. Loading the File Helper Before using the file helper, you must...

7 minutes read.

Download Helper Codeigniter

Download Helper Codeigniter: The download helper function is used to download data from the server to your computer. The data can be any format like text, jpg, mp3, mp4, etc. Loading...

2 minutes read.

CodeIgniter String Helper

The string helper file contains functions that allows separate operations with strings in CodeIgniter. Loading the String Helper Before using the string helper in the CodeIgniter application, you must load it in the controller...

7 minutes read.

CodeIgniter Security Helper

A Security helper file contains some predefined functions that are used to protect application from unauthorized access. Loading the Helper The following syntax is used to load the security helper in the CodeIgniter application. Syntax $this-> load->...

4 minutes read.

CodeIgniter Tutorial

What is CodeIgniter? CodeIgniter is an open-source framework for developing a dynamic web application with the use of PHP. It uses the MVC framework to develop the project, which is much...

3 minutes read.

Retrieve data from Database

Retrieve data from the Database Now we will discuss how we can retrieve data from the database that we have inserted to the employees table of the database in our previous topic “inserted...

2 minutes read.