CodeIgniter Controller for Sending Email via Gmail SMTP
Posted in post on June 12th, 2010 by Aditya – 3 Comments
function Index()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'SuperAwesomeAccount@gmail.com',
'smtp_pass' => 'SuperAwesomePassword'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n"); /* for some reason it is needed */
$this->email->from('SuperAwesomeAccount@gmail.com', 'Aditya Lesmana Test');
$this->email->to('SuperAwesomeReceiver@gmail.com');
$this->email->subject('This is an email test');
$this->email->message('it is working Darling
');
if($this->email->send())
{
echo 'Your email was sent, dammit';
}
else
{
show_error($this->email->print_debugger());
}
}
notice that I load the email library everytime this class is called and not via application/config/autoload.php
$this->load->library('email', $config);
and pay attention to
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'SuperAwesomeAccount@gmail.com',
'smtp_pass' => 'SuperAwesomePassword'
);
can be moved (not copy, MOVED) more ood-ly into config/email.php (in this case CI will try to look for config for ‘email’ controller at config folder named ‘email’. Inside config/email.php the code wil turn something like
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'SuperAwesome@gmail.com';
$config['smtp_pass'] = 'Alamak';
in which you need to change controller/email.php, removing unnecessary $config
$this->load->library('email', $config);
to
$this->load->library('email');
the first line is to prevent unauthorized access while the rest is pretty self explanatory.
ps: the closing statment for php is not mandatory. Omitting them is considered best practice
via
http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-3