Controller (Pages.php)
public function contact()
{
$this->load->library('email');
$this->load->library('form_validation');
//Set form validation
$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[4]|max_length[16]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|min_length[6]|max_length[60]');
$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[12]|max_length[200]');
//Run form validation
if ($this->form_validation->run() === FALSE)
{
$this->load->view('contact');
} else {
//Get the form data
$name = $this->input->post('name');
$from_email = $this->input->post('email');
$subject = $this->input->post('subject');
$message = $this->input->post('message');
//Web master email
$to_email = '[email protected]'; //Webmaster email, who receive mails
//Mail settings
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_user'] = '[email protected]'; // Your email address
$config['smtp_pass'] = 'mailpassword'; // Your email account password
$config['mailtype'] = 'html'; // or 'text'
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE; //No quotes required
$config['newline'] = "\r\n"; //Double quotes required
$this->email->initialize($config);
//Send mail with data
$this->email->from($from_email, $name);
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
if ($this->email->send())
{
$this->session->set_flashdata('msg','<div class="alert alert-success">Mail sent!</div>');
redirect('contact');
} else {
$this->session->set_flashdata('msg','<div class="alert alert-danger">Problem in sending</div>');
$this->load->view('contact');
}
}
Views (contact.php)
<div class="container">
<h2>Contact</h2>
<div class="row">
<div class="col-lg-6">
<?php echo $this->session->flashdata('msg'); ?>
<form action="<?php echo base_url('contact'); ?>" method="post">
<div class="form-group">
<input name="name" placeholder="Your name" type="text" value="<?php echo set_value('name'); ?>" class="form-control" />
<?php echo form_error('name', '<span class="text-danger">','</span>'); ?>
</div>
<div class="form-group">
<input name="email" placeholder="Your e-mail" type="text" value="<?php echo set_value('email'); ?>" class="form-control" />
<?php echo form_error('email', '<span class="text-danger">','</span>'); ?>
</div>
<div class="form-group">
<input name="subject" placeholder="Subject" type="text" value="<?php echo set_value('subject'); ?>" class="form-control" />
</div>
<div class="form-group">
<textarea name="message" rows="4" class="form-control" placeholder="Your message"><?php echo set_value('message'); ?></textarea>
<?php echo form_error('message', '<span class="text-danger">','</span>'); ?>
</div>
<button name="submit" type="submit" class="btn btn-primary" />Send</button>
</form>
</div>
</div>