Codeigniter Send Email With Gmail Smtp Protocol

Codeigniter Send Email With Gmail Smtp Protocol

In this Codeigniter send email tutorial , We’ll show you how to send email in codeigniter 3 using google gmail smtp with example. We will learn how to send email in codeigniter using SMTP driver.

We will give you very simple example of send email using codeigniter library to send email.

Contents

  • Download Codeigniter Project
  • Basic Configurations
  • Create Email.php In Config
  • Make Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ and also rename your project folder name to ci-crud.

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo';

New File Email.php In Config

Now we need to create email.php file inside the application/config/ folder. This is used to manage email settings or smtp details in this file. After create this file add the following code to email.php.

<?php 

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = 'your_email';
$config['smtp_pass'] = 'your_password';
$config['smtp_port'] = 465;

$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['newline'] = "\r\n"; 

Make Controller

Go to application/controllers/ and create a controller name Email.php. In this controller we will create some method/function name index() and send_mail() for sending email. Put the below code in your Email.php controller.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Email extends CI_Controller {
 
	 public function __construct()
	 	{
	 		parent::__construct();
			$this->load->helper('url');
			$this->load->config('email');
	 	}
 
 
	public function index()
	{
		$this->load->view('email_view');
	}
	public function send_mail()
	{

		$data['name'] = $this->input->post('name');
		$data['email'] = $this->input->post('email');
		$data['mobile_number'] = $this->input->post('mobile_number');
	
	    $this->load->library('email');

		$this->email->from('no-reply@tutsmake', 'Tutsmake')
	      	->to($data['email'])
	      	->subject('Welcome')
	      	->message($this->load->view('email_template', $data, true));

	    $this->email->send();	
     
        $arr = array('msg' => 'Something went wrong try again lator', 'success' =>false);

		if($this->email->send()){
		 $arr = array('msg' => 'Mail has been sent successfully', 'success' =>true);
		}
		echo json_encode($arr);

	}
}

Create Views

Go to application/views/ and create a two views. First view is used to showing the form and for sending email and second is used to send the email template for users.

first view name is email_view.php

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<style type="text/css">
  body{
    background: -webkit-linear-gradient(left, #0072ff, #00c6ff);
}
.contact-form{
    background: #fff;
    margin-top: 10%;
    margin-bottom: 5%;
    width: 70%;
}
.contact-form .form-control{
    border-radius:1rem;
}
.contact-image{
    text-align: center;
}
.contact-image img{
    border-radius: 6rem;
    width: 11%;
    margin-top: -3%;
    transform: rotate(29deg);
}
.contact-form form{
    padding: 14%;
}
.contact-form form .row{
    margin-bottom: -7%;
}
.contact-form h3{
    margin-bottom: 8%;
    margin-top: -10%;
    text-align: center;
    color: #0062cc;
}
.contact-form .btnContact {
    width: 50%;
    border: none;
    border-radius: 1rem;
    padding: 1.5%;
    background: #dc3545;
    font-weight: 600;
    color: #fff;
    cursor: pointer;
}
.btnContactSubmit
{
    width: 50%;
    border-radius: 1rem;
    padding: 1.5%;
    color: #fff;
    background-color: #0062cc;
    border: none;
    cursor: pointer;
}
.error{
  color:red;
}
</style>
<body>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  

<div class="container contact-form">
  <div class="contact-image">
      <img src="https://image.ibb.co/kUagtU/rocket_contact.png" alt="rocket_contact"/>
  </div>
  <form method="post" id="getInTouchForm">
      <div class="alert alert-success d-none" id="msg_div">
          <span id="res_message"></span>
      </div><br>
      <h3>Drop Us a Message</h3>
     <div class="row">
          <div class="col-md-6">
              <div class="form-group">
                  <input type="text" name="name" class="form-control" placeholder="Your Name " value="" />
              </div>
              <div class="form-group">
                  <input type="email" name="email" class="form-control" placeholder="Your Email" value="" />
              </div>
              <div class="form-group">
                  <input type="text" name="mobile_number" class="form-control" placeholder="Your Phone Number" maxlength="10" value="" />
              </div>
              <div class="form-group">
                  <input type="submit" name="btnSubmit" id="get_in_touch_btn" class="btnContact" value="Send Message" />
              </div>
          </div>
          <div class="col-md-6">
              <div class="form-group">
                  <textarea name="txtMsg" class="form-control" placeholder="Your Message *" style="width: 100%; height: 150px;"></textarea>
              </div>
          </div>
      </div>
  </form>
</div>
</body>

<script type="text/javascript">
  var BASE_URL = "<?php echo base_url(); ?>";
     if ($("#getInTouchForm").length > 0) {
     $("#getInTouchForm").validate({
          rules: {
            name: {
              required: true,
            },
            email: {
              required: true,
            },
            mobile_number: {
              required: true,
              maxlength: 10,
            },
            txtMsg: {
              required: true,
            }
          },
           messages: {
              name: {
                required: 'Please enter name',
              },
              email: {
                required: 'Please enter email',
              },
              mobile_number: {
                required: 'Please enter mobile number',
              },
              txtMsg: {
                required: 'Please enter message',
              }
             
            },
          submitHandler: function (form) {
            var oldval = $('#get_in_touch_btn').val();
            $('#get_in_touch_btn').prop('disabled', true);
            $('#get_in_touch_btn').val('Submitting..');
              $.ajax({
                  type: "POST",
                  url: BASE_URL  + "email/send_mail",
                  data: $(form).serialize(),
                  dataType: 'json'
              }).done(function (response) {
                  if (response.success == true) {
                      $('#get_in_touch_btn').val(oldval);
                      $('#get_in_touch_btn').prop('disabled', false);

                      $('#res_message').html(response.msg);
                      $('#res_message').show();
                      $('#msg_div').removeClass('d-none');

                      document.getElementById("getInTouchForm").reset(); 
                      setTimeout(function(){
                      $('#res_message').hide();
                      $('#msg_div').hide();
                      },10000);
                  
                  } else {
                      $('#get_in_touch_btn').val(oldval);
                      $('#get_in_touch_btn').prop('disabled', false);
                    
                  }
              });
              return false;
          }

      });

  }
</script>
</html>

second name is email_template.php

<!DOCTYPE html>
<html>
<head>
	<title>Hello world</title>
</head>
<body>
Hi, Your email id is <?php echo $email; ?>
</body>
</html>

Start Development server

For start development server, Go to the browser and hit below the url.

http://localhost/demo/email

Conclusion

In this codeigniter email send tutorial – We have successfully created email template and views and also sent email to given users email id.

You may like

  1. Codeigniter 3 Create First Ajax CRUD Application
  2. Upload Image/File Into Database Ajax Codeigniter
  3. Codeigniter Load Data While Scrolling Page with Ajax
  4. Export Data to Excel/CSV in Codeigniter Using PHPExcel
  5. Adding Multiple Markers To Google Maps From Database PHP Codeigniter
  6. Integrate Razorpay with PHP Codeigniter
  7. Implement Google Column Chart With PHP Codeigniter
  8. Google Bar & Line Charts Days Wise MySQL PHP Codeigniter
  9. Codeigniter Pagination Library Example
  10. Morris Area & Line Chart With Codeigniter Example

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *