Codeigniter Send Email with Gmail Smtp Example

In this tutorial, We’ll show you how to send email in codeigniter 3 using google gmail SMTP driver.

How to Send Email in CodeIgniter With GMAIL SMTP

Here are steps:

  • Download Codeigniter Project
  • Set Base URL
  • Create Email.php File
  • Create Controller
  • Create View
  • Test This Project

Download Codeigniter Project

Click and Download Codeigniter, and then unzip the ci setup in your local system xampp/htdocs/ system.

Set Base URL

Set base URL in application/config/config.php the file:

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

Create Email.php File

Create email.php in application/config/ folder, and setup smtp details in it:

<?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"; 

Create New Controller

Go to application/controllers/ and create a controller name Email.php.

Create some methods in the controller file to handle sending the email:

<?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 View

Create two views file in application/views/ folder, first view is used to show form and send email and second is used to send email template to users.

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>

email_template.php

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

Test This Project

Go to the browser and hit below the url.

http://localhost/demo/email

Conclusion

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

Recommended Tutorials

  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.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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