×

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

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 Date helper

A date helper file contains some predefined functions that work with date functions. Before using the date function in CodeIgniter, you have to load the date helper in the controller. For example: $this->load->helper(‘date’); Functions of...

12 minutes read.

HTML Table Class CodeIgniter

HTML Table Class The CodeIgniter framework provides an HTML Table Class that is used to develop an auto-generated table using a defined array or result sets of the database table. Loading an HTML Table Class...

8 minutes read.

CodeIgniter Language Class

Language Class The CodeIgniter’s language class contains the various functionality that is used to access the language-specific files and text line for the purposes of internationalization. This class provides you suitability to add or...

4 minutes read.

CodeIgniter CAPTCHA Helper

A CAPTCHA (Complete Automated Public Turning test to tell Computer and Humans Apart) helper is a function that is used in web application to check whether the user is human or machine. It...

3 minutes read.

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.

Image Manipulation Codeigniter

Image Manipulation A Codeigniter provides an image manipulation class that is used for resizing, cropping, rotation, and many other manipulation tasks. This class also support three major image libraries such as GD/GD2, NetPBM, and...

11 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.

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...

9 minutes read.

Migration Class CodeIgniter

The CodeIgniter framework provides the migration class that helps the web developers to create and handle databases in a structured and streamlined manner. The migration classes are very useful when more than...

6 minutes read.

Versions of CodeIgniter

CodeIgniter v3.1.11 (This is the current version which we will used in this tutorial)CodeIgniter v3.1.10CodeIgniter v3.1.9CodeIgniter v3.1.8CodeIgniter v3.1.7CodeIgniter v3.1.6CodeIgniter v3.1.5CodeIgniter v3.1.4CodeIgniter v3.1.3CodeIgniter v3.1.2CodeIgniter v3.1.1CodeIgniter v3.1.0CodeIgniter v3.0.6CodeIgniter...

1 minute read.

CodeIgniter URI Class

URI Class The CodeIgniter contains a URI class that is used to retrieve information from URI strings. It also provides suitability to get information from the re-routed segments. The system automatically initializes this...

6 minutes read.

Form Validation Library Codeigniter

Form Validation Library The Codeigniter provides a form validation library that contains predefined rules to validate the form fields. It also helps in optimizing the form validation code, which reduces the effort and time...

31 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.

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 Number helper

The number helper file contains some predefined function that deals with numeric data to display numbers in bytes format. Load a Number Helper You must load a number helper file in the controller to perform...

3 minutes read.

CodeIgniter Routes

The Routes are used to handle URL requests on the browser. It matches the URL request to the predefined routes in CodeIgniter. Therefore, a file must be predefined as a routes.php file to...

6 minutes read.

CodeIgniter HTML Helper

The HTML helper function is used in CodeIgniter to provide various functionality, such as headings, images, links, list tags, etc. Loading the HTML Helper Before using the html helper function, you must load the...

7 minutes read.

CodeIgniter Text Helper

The text helper contains the various function that is used to operate with text such as define a word limit and characters limit, conversion of word from ASCII to entities, etc. Loading the text...

4 minutes read.

Codeigniter Session Library

Session Library The session is an essential part of any application. It contains various functions to manage the users' status and track their activity while browsing on the site. For example,...

13 minutes read.