CodeIgniter - Load system library from my library not working - php

I'm trying to make my library to send email.
In my controller I set up as:
$this->load->library('MY_Email'); // My library has been loaded
File MY_Email.php
class MY_Email {
public $ci;
public $config;
public $email;
public function __construct () {
$ci = &get_instance();
$ci->load->config('email');
$this->config = array(
'protocol' => $ci->config->item('email_protocol'),
'smtp_host' => $ci->config->item('email_smtp_host'),
'smtp_port' => $ci->config->item('email_smtp_port'),
'smtp_timeout' => $ci->config->item('email_smtp_timeout'),
'smtp_user' => $ci->config->item('email_smtp_user'),
'smtp_pass' => $ci->config->item('email_smtp_pass'),
'charset' => $ci->config->item('email_charset'),
'mailtype' => $ci->config->item('email_mailtype'),
'validation' => $ci->config->item('email_validation')
);
$ci->load->library('email', $this->config);
/*This line print `Undefined property: Controller::$email` and result is NULL*/
var_dump($ci->email); die;
}
}
What is my wrong?
Thanks for any helps

Related

why did my attempt to send my email not work status HTTP 303 See Other in codeigniter

why is my attempt to send the email unsuccessful, I can't see the error, all I get is the http status code 303 See More
In my opinion, what I'm doing is in accordance with the official documentation https://codeigniter.com/userguide3/libraries/email.html
the result i expect is an email sent
Can anyone help me?
, How can I solve this?
config/email.php
$config['settings'] = array(
'smtp_host' => 'smtp.mailtrap.io',
'smtp_port' => '2525',
'smtp_user' => '9cf16dcde1asdasde5f8',
'smtp_pass' => '079205e1asdasd26bf43',
'from_email' => 'no-reply#test.com',
'from_name' => 'Test',
'protocol' => 'smtp',
'smtp_crypto' => 'tls',
'mailtype' => 'html',
'charset' => 'utf-8',
'newline' => "\r\n",
'crlf' => "\r\n",
);
libraries/Ah_Email.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Ah_Email {
public function __construct()
{
$CI =& get_instance();
$CI->load->config('email', true);
$this->configs = $CI->config->config['email'];
$CI->load->library('email');
$this->email = $CI->email;
}
public function send($email_to, $subject, $template, $template_vars = array(), $settings = array())
{
$settings = array_merge(
$this->configs['settings'],
$settings
);
$this->email->initialize($settings);
$this->email->from($settings['from_email'], $settings['from_name']);
if (isset($settings['send_email']) && $settings['send_email']) {
$this->email->to($email_to);
}
$CI =& get_instance();
$this->email->subject($subject);
$this->email->message($CI->load->view('emails/' . $template, $template_vars, true));
$res = $this->email->send();
return $res;
}
}
My Controller
public function SendMail() {
$this->load->library('ah_email', 'ah_email');
$send = $this->ah_email->send('receiver#gmail.com', 'Informasi Kode OTP Akun Kamu', 'example', array(
'username' => 'Ndo Malau',
'message' => 'Hello World',
'mailtype' => 'text',
));
if($send) {
$result = redirect(base_url('Systems/Users/index/'), $this->session->set_flashdata('succ_msg', 'success, email has been sending!'));
} else {
$result = redirect(base_url('Systems/Users/index/'), $this->session->set_flashdata('err_msg', 'failed, error while email sending'));
}
return $result;
}

How to send email using php codeigniter?

<?php
class SendEmail extends Controller
{
function SendEmail()
{
parent::Controller();
$this->load->library('email'); // load the library
}
function index()
{
$this->sendEmail();
}
public function sendEmail()
{
// Email configuration
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com.',
'smtp_port' => 465,
'smtp_user' => 'xxxx', // change it to yours
'smtp_pass' => 'xxxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from('xxxx', "Admin Team");
$this->email->to("xxxx");
$this->email->cc("xxxx");
$this->email->subject("This is test subject line");
$this->email->message("Mail sent test message...");
$data['message'] = "Sorry Unable to send email...";
if ($this->email->send()) {
$data['message'] = "Mail sent...";
}
// forward to index page
$this->load->view('index', $data);
}
}
?>
I get an error - I am doing it in codeigniter PHP Error was encountered
Severity: Compile Error
Message: Cannot redeclare SendEmail::sendEmail()
Filename: controllers/SendEmail.php
Line Number: 16
Backtrace:
Controller code
<?php
class SendEmail extends Controller
{
function __construct()
{
parent::__construct();
$this->load->library('email'); // load the library
}
function index()
{
$this->sendEmail();
}
public function sendEmail()
{
// Email configuration
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com.',
'smtp_port' => 465,
'smtp_user' => 'xxxx', // change it to yours
'smtp_pass' => 'xxxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from('xxxx', "Admin Team");
$this->email->to("xxxx");
$this->email->cc("xxxx");
$this->email->subject("This is test subject line");
$this->email->message("Mail sent test message...");
$data['message'] = "Sorry Unable to send email...";
if ($this->email->send()) {
$data['message'] = "Mail sent...";
}
// forward to index page
$this->load->view('index', $data);
}
}
?>

Consult email from the database and send

I am trying to send an email with this function, if I write the email statically, it works correctly, but when trying to query it from the database, the $email_user variable does not get the value of the sql query. What am I doing wrong ?
Model
public function send(){
$this->db->select('email_user');
$this->db->from('users');
$this->db->where('id_user= "8" ');
$email_user = $this->db->get()->row();
$this->load->library('email');
$this->email->from('xxxx#gmail.com');
$this->email->to($email_user);
$this->email->subject('example');
$this->email->message('Hello World');
$this->email->send();
}
Make sure you have set your email config and also try like below with db
public function send(){
$id = '8';
$this->db->where('id_user', $id);
$query = $this->db->get('users');
$row = $query->row();
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '****',
'smtp_pass' => '****',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('xxxx#gmail.com', 'Admin');
$this->email->to($row->email_user);
$this->email->subject('example');
$this->email->message('Hello World');
$this->email->send();
}

codeigniter 2.0.3-Fatal error

I am new to codeigniter and i tried a lesson from one of the tutorials but it throws the following error:
Class 'Controller' not found in
C:\xampp\htdocs\CodeIgniter\application\controllers\email.php
on line 3
My code:
<?php
class Email extends Controller{
function __construct()
{
parent::Controller();
}
function index()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'username' => 'saveniroj#gmail.com',
'password' => 'password'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('saveniroj#gmail.com', 'Niroj Shakya');
$this->email->to('saveniroj#gmail.com');
$this->email->subject('This is a test email');
$this->email->message('Oops This is Great.');
if($this->email->send())
{
echo 'Your email was sent, FOOL';
}
else
{
show_error($this->email->print_debugger());
}
}
}
?>
What's the problem?
Change the class definition to
class Email extends CI_Controller {
and in the __construct function
parent::CI_Controller();
In CodeIgniter 2, the default controller is CI_Controller and the default model is CI_Model, whereas in CodeIgniter 1 they were just Controller and Model.
Actually parent::CI_Controller(); needs to be parent::__construct();. PHP will fatal error unless you are on PHP 5.1.x which I believe will alias to PHP 4 style if its missing.

Problem using CodeIgniter to send emails through Gmail?

I'm trying to send an email in codeigniter via my Gmail account. My current code looks like this:
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'me#gmail.com',
'smtp_pass' => 'my_gmail_password',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('me#gmail.com', 'Me');
$this->email->to("me#gmail.com");
$this->email->subject('A test email from CodeIgniter using Gmail');
$this->email->message("A test email from CodeIgniter using Gmail");
$this->email->send();
However, this gives me the following errors:
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Connection timed out)
Filename: libraries/Email.php
Message: fwrite(): supplied argument is not a valid stream resource
Message: fgets(): supplied argument is not a valid stream resource
Any help to resolve this issue would be much appreciated! Thanks!
Note: I can assure you that my Gmail email & password are correct
The error means you cannot connect the the SMTP address you've entered.
you should use: smtp.gmail.com
Check following link for reference:
http://mail.google.com/support/bin/answer.py?answer=13287
You could download a nice little sparks package by "Shawn McCool" that utilizes "Swift-Mailer".
Check out his site for install instructions
Here is my configuration for sending out email's using a DRY approach(PHP 5.3.0 required!).
Config
|--mailer[dot]php
$config['swift_email_server'] = 'ssl://smtp.googlemail.com';
$config['swift_email_port'] = 465;
$config['swift_email_username'] = '######';
$config['swift_email_password'] = '######';
Libarary
|--MY_Email
class MY_Email extends CI_Email {
public function __construct(){
parent::__construct();
}
/**
* =========================================================================
* Parse's html email templates - initalised via swift-mailer
*
* #param mixed $data
* #param string $template
* #return html
*
* =========================================================================
*/
public function send_mail($data, $template){
//Anonymous functions are available since PHP 5.3.0
$callback = function ($matches) use ($data){
return ( isset($data[$matches[1]]) )
? $data[$matches[1]]
: $matches[0];
};
//Finds any matches in brackets [] and replaces them with data passed via callback
return preg_replace_callback(
'/\[(.*?)\]/',
$callback,
read_file(EMAIL_TEMPLATES . $template));
}
}
Email templates location defined in index.php
define('EMAIL_TEMPLATES', 'emailtemplates');
Controller
|--MY_Controller
class MY_Controller extends MX_Controller{
protected $user;
protected $swiftMailer = NULL;
public function __construct(){
parent::__construct();
$this->user = ($this->session->userdata('uid'))
? Member::find($this->session->userdata('uid')) : array();
$this->setup_profile();
$this->form_validation->set_error_delimiters('<p class="form-error">', '</p>');
}
public function setup_profile(){
$sections = array(
'config' => FALSE,
'http_headers' => FALSE,
'queries' => FALSE,
'memory_usage' => FALSE
);
$this->output->set_profiler_sections($sections);
if(ENVIRONMENT === 'development'){
$this->output->enable_profiler(TRUE);
}
}
protected function prep_email($data, $template){
$message =
Swift_Message::newInstance('Type your heading here...')
->setFrom($data['email_address'])
->setTo(array($this->config->item('primary_email'), $data['email_address']))
->setBody( $this->email->send_mail($data, $template))
->setContentType('text/html');
return ( $this->swiftMailer->send($message) );
}
}
Module
|--services // simple test module
public function arrange() {
$config = array(
array('field'=>'service', 'label'=>'Service', 'rules'=>'trim|required|max_lenght[128]'),
array('field'=>'num', 'label'=>'Numer of Sessions', 'rules'=>'trim|required|numeric'),
array('field'=>'request_date', 'label'=>'Request_date', 'rules'=>'trim|required'),
array('field'=>'note', 'label'=>'Note', 'rules'=>'trim|max_lenght[500]')
);
$this->form_validation->CI =& $this;
$this->form_validation->set_rules($config);
if($this->form_validation->run($this)){
$service = Service::find($this->input->post('service'));
if((int)$this->input->post('num') > 1){
$potential = ( $this->input->post('num') * $service->price );
}else{
$potential = $this->input->post('num');
}
$insert = array(
'service_id' => $this->input->post('service'),
'num' => $this->input->post('num'),
'request_date' => $this->input->post('request_date'),
'note' => serialize( $this->input->post('note') ),
'potential_income' => $potential,
'member_id' => $this->user->id,
'status' => 'pending'
);
$emaildata = array(
'service' => $service->slug,
'num' => $insert['num'],
'request_date' => $insert['request_date'],
'note' => $insert['note'],
'potential_income' => $potential,
'email_address' => $this->user->email_address,
'status' => 'pending',
'fullname' => $this->user->firstname . ' ' . $this->user->surname,
'message_sent' => date('M d h:iA'),
'site_link' => ''
);
if(Meeting::create($insert)){
if(parent::prep_email($emaildata, 'request_meeting[dot]html')){
$this->session->set_flashdata('success' ,'Request has been sent! You will recieve an email shortly from Paul');
//redirect('/');
}else{
$this->session->set_flashdata('error', 'Email service seems to be down at the moment');
//redirect('/');
}
}else{
$this->session->set_flashdata('error', 'Unable to request meeting at this time');
//redirect('/');
}
}else{
$this->meetings_form();
}
Hope this helps!

Categories