Cara kirim email dengan Codeigniter dan Ajax

Kali ini saya akan membahas bagaimana cara kirim email dengan Codeigniter dan Ajax, Fitur kirim email untuk beberapa kasus pembuatan aplikasi berbasis web kadang dibutuhkan, dan kasus saya adalah untuk mengirimkan email dari Form Contact web.

Berikut langkah – langkahnya :
1. Buat controller dengan nama Sendmail.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sendmail extends CI_Controller {

    public function index()
    {

        // untuk kirim data via model 
        $this->sendmail_m->message();

        //untuk menangkap data yang dikirim dari form contact
        $fname = $this->input->post('form_name');
        $femail = $this->input->post('form_email');
        $fsubject = $this->input->post('form_subject');
        $fmessage = $this->input->post('form_message');

        //set to_email id ke mana Anda ingin menerima email 
        $to_email1 = 'alamatGmail@gmail.com'; //contoh zai@gmail.com
        $recipientArr = array($to_email1);

        
        //Konfigurasi email 
        $config = Array(
            'useragent' => 'CodeIgniter',
            'protocol'  => 'smtp',
            'mailpath'  => '/usr/sbin/sendmail',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => 'alamatGmail@gmail.com',
            'smtp_pass' => 'PasswordGmail',
            'smtp_keepalive' => TRUE,
            'smtp_crypto' => 'SSL',
            'wordwrap'  => TRUE,
            'wrapchars' => 80,
            'mailtype'  => 'html',
            'charset'   => 'utf-8',
            'validate'  => TRUE,
            'crlf'      => "\r\n",
            'newline'   => "\r\n"
        );


        //load library email dan konfigurasinya
        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");   

        //Kirim email
        //email dan nama pengirim 

        $this->email->from($femail, $fname);
        //email penerima 

        $this->email->to($recipientArr);

        //subject email
        $this->email->subject($fsubject);

        //isi email
        $this->email->message($fmessage);

        $result = $this->email->send();
        if ($this->email->send())
        {

            // berhasil
            echo 1;
        }
        else
        {
            // gagal
            echo 0;
        }
    }
} 

2. Buat model dengan nama Sendmail_m.php

<?php
class Sendmail_m extends CI_Model{

 //simpan pesan ke database
 function message() {

    //untuk menangkap data yang dikirim dari form contact
    $fname = $this->input->post('form_name');
    $femail = $this->input->post('form_email');
    $fsubject = $this->input->post('form_subject');
    $fmessage = $this->input->post('form_message');

    $data=array(
       "f_name"=>$fname,
       "f_email"=>$femail,
       "f_subject"=>$fsubject,
       "f_message"=>$fmessage,
    );
    return $this->db->insert("t_message",$data);
    }

} 

3. Buat view dengan nama form_contact.php

<h4>Kirim Pesan Kamu</h4>
<form action="javascript:void(0);" id="form_contact" method="post">
    <input type="text" id="form_name" name="form_name" placeholder="Nama Lengkap" required="required">
    <input type="email" id="form_email" name="form_email" placeholder="Email" required="required">
    <input type="text" id="form_subject" name="form_subject" placeholder="Subject" required="required">
    <textarea id="form_message" name="form_message" cols="30" rows="10" placeholder="Isi Pesan" required="required"></textarea>
    <button type="submit">KIRIM</button>
    <span class="msg_contact"></span>
</form>

Dan buat ajax yang disimpan tepat di bawah html form contact artinya satu file dengan form_contact.php

<script>
    $("#form_contact").submit(function() {
        $.ajax({
            url :"<?php echo site_url()?>sendmess",
            type:"POST",
            data: $("#form_contact").serialize(),
            beforeSend: function() {
                $('.msg_contact').html('<img src="<?php echo   base_url();?>theme/images/loader/loadingblue.gif"> Cheking...');
            },
            success: function(data){
                if(data!='0'){
                   alert("Pesan berhasil di kirim");
                }else{
                    alert("Pesan gagal di kirim");
                }
                $('.msg_contact').html('');   
            },
            error: function(jqXHR, textStatus, errorThrown){ alert("Gagal memproses"); $('.msg_contact').html(''); return false;}                          
        });
    });    
</script>

Biasanya script ini akan berjalan saat sudah dinaikan ke server hosting. Selamat mencoba dan silahkan dimodifikasi sesuai kebutuhan kawan – kawan.

Terimakasih Salam Coding.

Leave a Reply

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