Send Email With Attachment using Codeigniter and AJAX
Before started to implement the Send Email With Attachment, look files structure:
- codeigniter-send-email-with-attachment
- application
- config
- constants.php
- routes.php
- controllers
- Contact.php
- views
- Contact
- index.php
- mailTemplate
- contactaForm.php
- templates
- header.php
- footer.php
- Contact
- config
- system
- index.php
- assets
- css
- style.css
- js
- custom.js
- application
A simple step-by-step guide to help you Send Email With Attachment Codeigniter
Step 1: Load “email” class in controller.
1 2 3 |
<?php $this->load->library('email'); ?> |
Step 2: Define constants
Update file named
constants.php
inside “application/config/” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php define('TO_MAIL', 'xxxxx@xxx.com'); define('FROM_MAIL', 'xxxxx@xxx.com'); define('FROM_TEXT', 'TECHARISE'); define('DATE_FORMAT_SIMPLE', 'Y-m-d'); define('PROTOCOL', 'smtp'); define('SMTP_HOST', 'smtp.gmail.com'); define('SMTP_PORT', 587); define('SMTP_USER', 'XXXXX'); define('SMTP_PASS', 'XXXXX'); define('MAILTYPE', 'html'); define('CHARSET', 'utf-8'); ?> |
Step 3: Create a controller file
Create a controller file named
Contact.php
inside “application/controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
<?php /** * @package Contact : Send Email With Attachment using Codeigniter * * @author TechArise Team * * @email info@techarise.com * * Description of Contact Controller */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Contact extends CI_Controller { public function __construct() { parent::__construct(); } // contact page public function send() { $data['page'] = 'contact-form'; $data['title'] = 'Send Email With Attachment using Codeigniter and AJAX | TechArise'; $this->load->view('contact/index', $data); } // send information public function sendWithAttachData() { $json = array(); $name = $this->input->post('fullname'); $email = $this->input->post('email'); $comment = $this->input->post('comment'); // name validation if(empty(trim($name))){ $json['error']['fullname'] = 'Please enter full name'; } // email validation if(empty(trim($email))){ $json['error']['email'] = 'Please enter email address'; } // check email validation if ($this->validateEmail($email) == FALSE) { $json['error']['email'] = 'Please enter valid email address'; } // comment validation if(empty($comment)){ $json['error']['comment'] = 'Please enter comment'; } // file upload validation if(empty($_FILES['uplfile'])){ $json['error']['uplfile'] = 'Please Choose file'; } if(empty($json['error'])){ // load email lib $this->load->library('email'); //SMTP & mail configuration $config = array( 'protocol' => PROTOCOL, 'smtp_host' => SMTP_HOST, 'smtp_port' => SMTP_PORT, 'smtp_user' => SMTP_USER, 'smtp_pass' => SMTP_PASS, 'mailtype' => MAILTYPE, 'charset' => CHARSET, ); $message=''; $bodyMsg = '<p style="font-size:14px;font-weight:normal;margin-bottom:10px;margin-top:0;">'.$comment.'</p>'; $delimeter = $name."<br>".$email; $dataMail = array('topMsg'=>'Hi Team', 'bodyMsg'=>$bodyMsg, 'thanksMsg'=>'Best regards,', 'delimeter'=> $delimeter); $this->email->initialize($config); $this->email->from($email, $name); // set to email $this->email->to(TO_MAIL); $this->email->subject('Contact Form with Attachment'); // call mail Template $message = $this->load->view('mailTemplate/contactaForm', $dataMail, TRUE); $this->email->message($message); // with file attachment if (!empty($_FILES['uplfile'])) { $this->email->attach($_FILES['uplfile']['tmp_name'], $_FILES['uplfile']['name']); } $status = $this->email->send(); $this->email->clear(TRUE); if(!empty($status)){ $json['msg'] = 'success'; } else { $json['msg'] = 'failed'; } } $this->output->set_header('Content-Type: application/json'); echo json_encode($json); } // check email validation public function validateEmail($email) { return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE; } } ?> |
Step 4: Create a view
Create a view file named
index.php
inside “application/views/contact” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?php $this->load->view('templates/header');?> <!-- container --> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Send Email With Attachment Codeigniter</h2> </div> <span id="success-msg"></span> <form class="ajax-contact-a-frm" id="ajax-contact-a-frm" enctype="multipart/form-data" method="post" accept-charset="utf-8"> <div class="row justify-content-center"> <div class="col-12 col-md-8 col-lg-6 pb-5"> <!--Form with header--> <div class="card border-info rounded-0"> <div class="card-header p-0"> <div class="bg-info text-white text-center py-2"> <h3><i class="fa fa-envelope"></i> Contac Form</h3> </div> </div> <div class="card-body p-3"> <!--Body--> <div class="form-group"> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text"><i class="fa fa-user text-info"></i></div> </div> <input type="text" class="form-control input-ca-fullname" id="fullname" name="fullname" placeholder="Full name *"> </div> </div> <div class="form-group"> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text"><i class="fa fa-envelope text-info"></i></div> </div> <input type="email" class="form-control input-ca-email" id="email" name="email" placeholder="Email *"> </div> </div> <div class="form-group"> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text"><i class="fa fa-comment text-info"></i></div> </div> <textarea class="form-control input-ca-comment" id="comment" name="comment" placeholder="Message"></textarea> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupFileAddon01"><i class="fa fa-paperclip text-info"></i></span> </div> <div class="custom-file"> <input type="file" name="uplfile" class="custom-file-input input-ca-uplfile" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01"> <label class="custom-file-label" for="inputGroupFile01" data-browse="Choose File">File name</label> </div> </div> </div> <div class="text-center"> <button type="button" id="contact-send-a" class="btn btn-info btn-block rounded-0 py-2"><i class="fa fa-paper-plane" aria-hidden="true"></i> Send</button> </div> </div> </div> </div> </div> </form> </div> </section> <?php $this->load->view('templates/footer');?> |
Step 5: Create a view(mailTemplate)
Create a view file named
contactaForm.php
inside “application/views/mailTemplate” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width"/> </head> <body style="width:100%;height:100%;background:#efefef;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:none;color:#3E3E3E;font-family:Helvetica, Arial, sans-serif;line-height:1.65;margin:0;padding:0;"> <table border="0" cellpadding="0" cellspacing="0" style="width:100%;background:#efefef;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:none;color:#3E3E3E;font-family:Helvetica, Arial, sans-serif;line-height:1.65;margin:0;padding:0;"> <tr> <td valign="top" style="display:block;clear:both;margin:0 auto;max-width:580px;"> <table border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;"> <tr> <td valign="top" align="center" class="masthead" style="padding:20px 0;background:#03618c;color:white;"> <h1 style="font-size:32px;margin:0 auto;max-width:90%;line-height:1.25;"> <a href="<?php print site_url(); ?>" target="_blank" style="text-decoration:none;color:#ffffff;">TECHARISE</a> <p style="margin-bottom:0;line-height:12px;font-weight:normal;margin-top:15px;font-size:18px;"></p> </h1> </td> </tr> <tr> <td valign="top" class="content" style="background:white;padding:20px 35px 10px 35px;"> <h4 style="font-size:20px;margin-bottom:10px;line-height:1.25;"><?php print $topMsg; ?>,</h4> <?php print $bodyMsg; ?> </td> </tr> <tr> <td valign="top" style="display:block;clear:both;margin:0 auto;max-width:580px;"> <table border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;"> <tr> <td valign="top" class="content thanksMsg" style="background:white;padding:10px 35px 20px 35px;"> <p style="font-size:14px;font-weight:normal;margin-top:0;margin-bottom:5px;"><?php print $thanksMsg; ?></p> <p style="font-size:14px;font-weight:normal;margin-top:0;margin-bottom:5px;"><?php print $delimeter; ?></p> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </body> </html> |
Step 6: Create a AJAX file
Create a js file named
custom.js
inside “assets/js” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<script> jQuery(document).on('click', 'button#contact-send-a', function() { var formData = new FormData(); formData.append('fullname', jQuery('form#ajax-contact-a-frm').find('.input-ca-fullname').val()); formData.append('email', jQuery('form#ajax-contact-a-frm').find('.input-ca-email').val()); formData.append('comment', jQuery('form#ajax-contact-a-frm').find('.input-ca-comment').val()); formData.append('uplfile', jQuery('form#ajax-contact-a-frm').find('input.input-ca-uplfile')[0].files[0]); jQuery.ajax({ url:baseurl+'contact/sendWithAttachData', type: 'post', data: formData, cache: false, processData: false, contentType: false, dataType:'json', beforeSend: function () { jQuery('button#contact-send-a').button('loading'); }, complete: function () { jQuery('button#contact-send-a').button('reset'); jQuery("form#ajax-contact-a-frm").find('textarea, input, file').each(function () { jQuery(this).val(''); }); setTimeout(function () { jQuery('span#success-msg').html(''); }, 4000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { for (i in json['error']) { var element = $('.input-ca-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<small class="text-danger">' + json['error'][i] + '</small>'); } else { $(element).after('<small class="text-danger">' + json['error'][i] + '</small>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert">×</button>Your query has been successfully submitted.</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |