Monday, November 28, 2016

CodeIgniter Email Tutorial

Sending email in codeIgniter is much easier than you would imagine. At the end of this tutorial you would be able to send email through form.
Form

Before we start coding, we need to change some settings in our gmail account. We need to allow less secure apps to access our gmail account. To do that click here, make sure to turn it on.
Less



CodeIgniter provides the following features for sending emails
  • Multiple Protocol --SMTP, Sendmail, Mail
  • TLS and SSL Encryption for SMTP
  • Multiple Recipient
  • CC and BCC
  • Html or Plain email content
  • Attchments
  • Word wrapping
  • Priorities
  • BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
  • Email Debugging tools

Email Preferences

The following is a list of all the preferences that can be set when sending email.
Preference Default Value Options Description
useragent CodeIgniter None The “user agent”.
protocol mail mail, sendmail, or smtp The mail sending protocol.
mailpath /usr/sbin/sendmail None The server path to Sendmail.
smtp_host No Default None SMTP Server Address.
smtp_user No Default None SMTP Username.
smtp_pass No Default None SMTP Password.
smtp_port 25 None SMTP Port.
smtp_timeout 5 None SMTP Timeout (in seconds).
smtp_keepalive FALSE TRUE or FALSE (boolean) Enable persistent SMTP connections.
smtp_crypto No Default tls or ssl SMTP Encryption
wordwrap TRUE TRUE or FALSE (boolean) Enable word-wrap.
wrapchars 76 Character count to wrap at.
mailtype text text or html Type of mail. If you send HTML email you must send it as a complete web page. Make sure you don’t have any relative links or relative image paths otherwise they will not work.
charset $config['charset'] Character set (utf-8, iso-8859-1, etc.).
validate FALSE TRUE or FALSE (boolean) Whether to validate the email address.
priority 3 1, 2, 3, 4, 5 Email Priority. 1 = highest. 5 = lowest. 3 = normal.
crlf \n “\r\n” or “\n” or “\r” Newline character. (Use “\r\n” to comply with RFC 822).
newline \n “\r\n” or “\n” or “\r” Newline character. (Use “\r\n” to comply with RFC 822).
bcc_batch_mode FALSE TRUE or FALSE (boolean) Enable BCC Batch Mode.
bcc_batch_size 200 None Number of emails in each BCC batch.
dsn FALSE TRUE or FALSE (boolean) Enable notify message from server

Sending an Email

First, we need to load the email library with our prefered configuration. What we're doing is overriding the default configuration, you don't need to change anything if you prefer to use the default configuration. In this tutorial, though, we want to override some of the configuration settings with the following.
$config = array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'example@example.com',
        'smtp_pass' => 'password',
        'mailtype'  => 'html', 
        'charset'   => 'iso-8859-1'
    );
    $this->load->library('email', $config);
You could use several smtp ports which inclues 465, 587, and 25 (default).
We can now use the email library to send our email message. To do that, simply set the from(), to(), subject(), and message().
$this->email->from('your@example.com', 'Your Name');
    $this->email->to('someone@example.com');
     
    $this->email->subject('Email Test');
    $this->email->message('Testing the email class.');
After that, execute the send() function as shown below.
$this->email->send();

Example

Go ahead and create a file and name it Email_controller.php then save it in "application/controllers/". Afterwads, paste the following code inside your controller.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   class Email_controller extends CI_Controller { 
 
      function __construct() { 
         parent::__construct(); 
         $this->load->helper(array('form','url'));
         
      } 
        
      public function index() { 
    
         $this->load->helper('form'); 
         $this->load->view('email_form'); 
      } 
  
      public function send_mail() {
         $this->load->library(array('session', 'form_validation', 'email'));
         $this->form_validation->set_error_delimiters('<span class="text-danger">', '</span>');
         $this->_validate();
         $response= false;
         if(!$this->form_validation->run()){
            $this->load->view('email_form');
         }
         else{
            $from_email = "kodingmadesimple@gmail.com"; //Change this with your email
            $from_name = "Carl";//change this with your name
            $to_email = $this->input->post('email');
            $subject = $this->input->post('subject');
            $message = $this->input->post('message');
      
            $this->email->set_newline("\r\n");//must be included, won't send otherwise.
            $this->email->from($from_email, $from_name); 
            $this->email->to($to_email);
            $this->email->subject($subject); 
            $this->email->message($message);
      
            //Send mail 
            if($this->email->send()){
               $this->session->set_flashdata("message","<span class='alert alert-success col-xs-12' role='alert'>Successully sent.</span>"); 
            }
            else {
               $this->session->set_flashdata("message","<span class='alert alert-danger col-xs-12' role='alert'>An error occured while sending your email, please try again.</span>"); 
               // show_error($this->email->print_debugger());//Uncomment this code if you want to know more about the error.
            }
            $this->load->view('email_form'); 
         }
      } 
      public function _validate(){
         $rules = array(
            array(
               'field'  => 'name',
               'label'  => 'Name',
               'rules'  => 'required|trim'
            ),
            array(
               'field'  => 'email',
               'label'  => 'Email',
               'rules'  => 'required|trim|valid_email'
            ),
            array(
               'field'  => 'subject',
               'label'  => 'Subject',
               'rules'  => 'required|trim'
            ),
            array(
               'field'  => 'message',
               'label'  => 'Message',
               'rules'  => 'required|trim'
            )
         );
         $this->form_validation->set_rules($rules);
      }
   } 
?>
You'll notice that we don't have our "$config" settings here, well, you may put it here but you would have to repeat the code every time you want to send an email which is repetitive, not unless you're using multiple email account. But in most cases you'll be using just one email configuration setting for sending out emails. To do that, create a file in "application/config/" folder and save it as "email.php" then paste the following.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => 'kodingmadesimple@gmail.com',//Change this with your email
            'smtp_pass' => 'password',//Change this with your email password
            'mailtype'  => 'html', 
            'charset'   => 'iso-8859-1'
        );
You don't need to do anything, it's already loaded for you. Data Validation is very important in building web application. It ensures that user inputs are valid for the processing or for storage. Doing this preventing undesired application behaviours.

Now that we've created our controller, we need to create a view file and save it as "email_form" in "application/views/" folder. Then paste the following code.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Contact Form Example</title>
    <!--load bootstrap css-->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <style>
      .container {
         height: 100vh;
         display: flex;
         align-items: center;
         justify-content: center;
      }
      textarea{
         resize:vertical;
      }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
    <div class="col-xs-12">
        <div class="col-md-6 col-md-offset-3 well">
            <?php $attributes = array("class" => "form-horizontal", "name" => "send_mail");
            echo form_open("/Email_controller/send_mail", $attributes);?>
            <fieldset>
            <legend class="text-center">Send Email</legend>
            <div class="form-group">
                <div class="col-md-12">
                    <label for="name" class="control-label">Name</label>
                </div>
                <div class="col-md-12">
                    <input class="form-control" name="name" placeholder="ex. John" type="text" value="<?php echo set_value('name'); ?>" />
                    <span class="text-danger"><?php echo form_error('name'); ?></span>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-12">
                    <label for="email" class="control-label">Email ID</label>
                </div>
                <div class="col-md-12">
                    <input class="form-control" name="email" placeholder="ex. john@gmail.com" type="text" value="<?php echo set_value('email'); ?>" />
                    <span class="text-danger"><?php echo form_error('email'); ?></span>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-12">
                    <label for="subject" class="control-label">Subject</label>
                </div>
                <div class="col-md-12">
                    <input class="form-control" name="subject" placeholder="Your Subject" type="text" value="<?php echo set_value('subject'); ?>" />
                    <span class="text-danger"><?php echo form_error('subject'); ?></span>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-12">
                    <label for="message" class="control-label">Message</label>
                </div>
                <div class="col-md-12">
                    <textarea class="form-control" name="message" rows="4" placeholder="Your Message"><?php echo set_value('message'); ?></textarea>
                    <span class="text-danger"><?php echo form_error('message'); ?></span>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-12">
                    <input name="submit" type="submit" class="btn btn-success pull-right" value="Send" />
                </div>
            </div>
            </fieldset>
            <?php echo form_close(); ?>
            <?php echo $this->session->flashdata('message'); ?>
        </div>
    </div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
If user inputs passes the validation rules which we defined on our "_validate" function in our "Email_controller", a flash variable message is set and user is redirected to the form wherein we printed out the message variable at the bottom of the form. Form error messages are printed when it fail the rules we set.

No comments:

Post a Comment