Error Sending Email in Codeigniter 2 - php

I am new in codeigniter framework. I'm trying to send email but I have the problem:
Call to undefined method CI_Loader::libary()
here is my script on controller :
class Email extends CI_Controller{
function __construct()
{
parent::__construct();
}
function index()
{
$config = array(
'protocol' => 'smtp',
'smtp_host'=>'ss://smtp.googlemail.com',
'smtp_port'=>465,
'smtp_user'=>'thaitea.lumajang#gmail.com',
'smtp_pass'=>'thaitealumajang1'
);
$this->load->libary('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('thaitea.lumajang#gmail.com','Tri Wicaksono');
$this->email->to('cha8agust#gmail.com');
$this->email->subject('This is an email test');
$this->email->message('It is working bro');
if($this->email->send())
{
echo 'Your email send';
} else {
show_error($this->email->print_debbuger());
}
}
}

I already find out the answer.
There is wrong typing in $this->load->libary.
It should be $this->load->library - there is a missing r in library word.

Related

Show the subject and message sending email with Mail::to

I have the code below to send emails using the Mail::to function. But Im not understanding how to set the subject and body of the message with the Mail::to function. I have the code below that is working to send emails but without subject and the $message is also not appearing in the email.
Do you know how to properly achieve that? (Have subject and the $request->message in the email using Mail::to)
public function send(Request $request, $id){
$conference = Conference::find($id);
if($request->send_to == "participant"){
// if is to send only 1 email the Mail::to is called directly here
Mail::to($request->participant_email)->send(new Notification($conference));
return;
}
if($request->send_to == "all"){
// $sendTo = query to get a set of emails to send the email
}
else{
// $sendTo = query to get a another set of emails to send the email
}
foreach($sendTo as $user){
$usersEmail[] = $user->email;
}
$message = $request->message;
$subject = $request->subject;
foreach ($usersEmail as $userEmail){
Mail::to($userEmail)->send(new Notification($conference, $message));
}
}
In the class Notification I have:
class Notification extends Mailable
{
public $conference;
public function __construct(Conference $conference)
{
$this->conference = $conference;
}
public function build()
{
return $this->markdown('emails.notification');
}
}
In the view notifications.blade.php I have:
#component('mail::message')
# Notification relative to {{$conference->name}}
{{$message}}
Thanks,<br>
{{ config('app.name') }}
#endcomponent
Try something like this:
$emailData = array(
/* Email data */
'email' => 'user#email.com',
'name' => 'User name',
'subject' => 'Email subject',
);
Mail::send('emails.template_name', ['emailData' => $emailData], function ($m) use ($emailData) { // here it is a closure function, in which $emailData data is available in $m
$m->from('info#domain.com', 'Domain Name');
$m->to($emailData['email'], $emailData['name'])->subject($emailData['subject']);
});
try
{
Mail::send('emails.contact_form', ['data' => $data],
function($message) use ($data)
{
$message->from('emailasinenv#hosting.com', 'ShortName');
$message->to( $data['adminEmail'] )->subject("Contact Form" );
});
return true;
}
catch (\Exception $ex) {
$ex->getMessage();
return false;
}
As you already have one template in your code use that template, Pass the message to template
$subject = 'Email Subject';
Mail::send('emails.notification', ['message' => $message], function ($mail) use ($userEmail, $subject) {
$mail->from('info#domain.com', 'Domain Name');
$mail->to($userEmail)->subject($subject);
});

How to merge session data into a function using CodeIgniter?

I've asked this subject in another topic but that topic has gone cold and I've directed this topic to the core of the problem.
I've loaded the session library in the previous page and have no issue with the function working in that page.
But it is the next page where I'm having problems. I get the error "Unexpected T_VARIABLE".
I've read the topic on How to solve syntax errors. That topic suggests the line before is usually the problem line, usually by a missing semicolon or bracket.
This is the coding;
public function index()
{
$this->load->model('Code_model', 'code_model');
$this->session->email //This is the problem line
$email = $this->session->email
$code = $this->input->post('code');
if ($this->code_model->find_code($email, $code))
{
$this->load->view('username');
}
else
{
$this->load->view('codeincorrect');
}
}
I've tried putting a semicolon at the end. And tried adding - userdata('email');
And tried having a separate function containing the problem line with its own brackets. And tried deleting the problem line & the line below. When deleted $email cannot be found.
But nothing works.
Is there somebody who understands how sessions work and how they can be integrated into a function?
Update
This is the Controller coding of the previous page, which works good.
function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function index()
{
$this->load->model('Email_model', 'email_model');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'required|min_length[10]|max_length[40]|valid_email|is_unique[tbl_members.email_address]', array(
'required' => 'You have not entered an %s address.', 'min_length' => 'Your %s address must be a minimum of 10 characters.',
'max_length' => 'Your %s address must be a maximum of 40 characters.', 'valid_email' => 'You must enter a valid %s address.',
'is_unique' => 'That %s address already exists in our Database.'));
if ($this->form_validation->run() == FALSE) // The email address does not exist.
{
$this->load->view('email');
}
else
{
$email = $this->input->post('email');
$random_string = chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . chr(rand(65,90));
$code = $random_string;
$this->email_model->insert_email($email, $code);
}
}
2nd Update - This is the coding for the 2 Controllers and 2 Models
Email Controller
class Email extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function index()
{
$this->load->model('Email_model', 'email_model');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'required|min_length[10]|max_length[40]|valid_email|is_unique[tbl_members.email_address]', array(
'required' => 'You have not entered an %s address.', 'min_length' => 'Your %s address must be a minimum of 10 characters.',
'max_length' => 'Your %s address must be a maximum of 40 characters.', 'valid_email' => 'You must enter a valid %s address.',
'is_unique' => 'That %s address already exists in our Database.'));
if ($this->form_validation->run() == FALSE) // The email address does not exist.
{
$this->load->view('email');
}
else
{
$email = $this->input->post('email');
$random_string = chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . chr(rand(65,90));
$code = $random_string;
$this->email_model->insert_email($email, $code);
$this->load->library('email'); // Not sure if this works - testing from localhost
$this->email->from('<?php echo WEBSITE_NAME; ?>', '<?php echo WEBSITE_NAME; ?>'); // Not sure if this works - testing from localhost
$this->email->to('$email'); // Not sure if this works - testing from localhost
$this->email->subject('Code.'); // Not sure if this works - testing from localhost
$this->email->message('Select & Copy this code, then return to the website. - ','$code'); // Not sure if this works - testing from localhost
$this->email->send(); // Not sure if this works - testing from localhost
$this->load->view('code');
}
}
}
Email Model
class Email_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert_email($email, $code)
{
$data = array(
'email_address' => $email,
'pass_word' => $code
);
$this->db->insert('tbl_members', $data);
return $this->db->insert_id();
}
}
Code Controller
class Code extends CI_Controller
{
public function index()
{
$this->load->model('Code_model', 'code_model');
$this->session->email // Problem line - syntax error, unexpected '$email' (T_VARIABLE)
$email = $this->session->email
$code = $this->input->post('code');
if ($this->code_model->find_code($email, $code))
{
$this->load->view('username');
}
else
{
$this->load->view('codeincorrect');
}
}
}
Code Model
class Code_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function find_code($code,$email)
{
$this->db->select('user_id');
$this->db->where('email_address', $email);
$this->db->where('pass_word', $code);
$code = $this->db->get('tbl_members');
if ($code->result())
{
return $this->db->delete('pass_word', $code);
}
}
}
Make sure the sessions library is loaded. You can do this manually by saying:
$this->load->library('session');
But if you want it loaded at all times, go to your autoload.php file and make sure sessions is added in the autoload['libraries'] area.
Your code looks like the buggy. Please check followings.
In PHP statements are ended by semi-colon (;)
$this->session->email : returns the value of email element from session array and it should be assigned, like the next line as in your code $email = $this->session->email.
Check whether the email is set in the session or not print_r($this->session->all_userdata());
Best of luck!

Sending Email after insertion of data using codeigniter php

Sending email after inserting the data into database using codeigniter PHP is not working.Data is inserting succesfully but the MAIL functionality is not working getting as www.hostname.com page isn’t working.Can any one help me this.Thanks in advance.Here is my code.
Controller:
class Blog extends CI_Controller
{
function __construct()
{
parent::__construct();
//here we will autoload the pagination library
$this->load->model('blogs_model');
$this->load->library('email');
}
function addcomments()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('first_name','First Name' , 'required');
$this->form_validation->set_rules('email','Email');
$this->form_validation->set_rules('location','Location');
$this->form_validation->set_rules('description','Description');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='blogs';
$this->load->view('templates/template',$data);
}
else
{
//insert the user registration details into database
$data=array(
'blog_id'=>$this->input->post('bl_id'),
'first_name'=>$this->input->post('first_name'),
'email'=>$this->input->post('email'),
'description'=>$this->input->post('description'),
'location'=>$this->input->post('location')
);
// insert form data into database
if ($this->blogs_model -> insertcomments($data))
{
// send email
if ($this->blogs_model->send_mail($this->input->post('email')))
{
// successfully sent mail
$this->flash->success('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect("blog");
}
else
{
// error
$this->flash->success('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect("blog");
}
}
else
{
// error
$this->flash->success('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('blog');
}
}
}
}
Model:
function insertcomments($data)
{
return $this->db->insert('comments', $data);
//$this->db->insert('comments',$data);
//return $this->input->post('bl_id');
}
function sendEmail($to_email)
{
//configure email settings
$config=Array(
'protocol'=> 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com', //smtp host name
'smtp_port' => '465', //smtp port number
'smtp_user' => 'xxxx#gmail.com',
'smtp_pass' => '************', //$from_email password
'mailtype' =>'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
//send mail
$this->load->library('email',$config);
$this->email->from('xxxx#gmail.com', 'Admin');
$this->email->to('yyy#gmail.com');
$this->email->subject('Comments');
$this->email->message('Testing');
$this->email->set_newline("\r\n");
return $this->email->send();
}
You are using wrong method name for sending email in your controller:
$this->blogs_model->send_mail($this->input->post('email'))
Correct function name is sendEmail()
$this->blogs_model->sendEmail($this->input->post('email'))
Check your code:
You should change function "send_mail" in your controller because in model you used "sendEmail".
Change in to your controller :
$this->blogs_model->sendEmail($this->input->post('email'))
I think the problems in your code is this line
smtp_host' => 'ssl://smtp.googlemail.com
try instead: smtp_host' => 'http://smtp.gmail.com

Email class - CodeIgniter PHP - Send email to multiple members

I have been trying to send an email to multiple members within my database. I managed to get the application to send one email to specific users emails, but when I use a list function I get errors (undefined index) that are supposedly in the libraries/email.php file but as far as I am aware I should not have to change the email library file. I am working on my localhost and here is the code:
function send(){
$this->load->model('mail_model', 'emails');
$emails=$this->emails->get_emails();
foreach($emails as $row){
if($row['email']){
$this->email->set_newline("\r\n");
$this->email->from('myemail#test.com', 'my name');
$this->email->to($row['email']);
$this->email->subject('Test multiple receivers');
$this->email->message('Test');
$this->email->send();
echo $this->email->print_debugger();
$this->email->clear();
$path = $this->config->item('server_root');
}
if($this->email->send())
{
//echo 'Your email was sent.';
$data['main_content'] = 'signup_confirmation';
$this->load->view('includes/template', $data);
}
else
{
show_error($this->email->print_debugger());
}
}
}
I have already autoloaded the email library in the config files. This is the code from the model:
class Mail_model extends CI_Model
{
function get($id = null)
{
$this->db->select('mailing_member_id', 'mailing_list_id', 'email_address');
$this->db->from('mailing_members');
if (!is_null($id)) $this->db->where('mailing_member_id', $id);
$this->db->order_by('mailing_member_id', 'desc');
return $this->db->get()->result();
}
Your model's get()method returns an object instead of an array. Try:
return $this->db->get()->result_array();
Also, you need $row['email_address']not $row['email'] for the ifstatement.

Adding custom callback to Codeigniter Form Validation

I want to limit my registration to emails with #mywork.com I made the following in My_Form_validation.
public function email_check($email)
{
$findme='mywork.com';
$pos = strpos($email,$findme);
if ($pos===FALSE)
{
$this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
return FALSE;
}
else
{
return TRUE;
}
}
I use it as follows. I use CI rules for username and password and it works, for email it accepts any email address. Any I appreciate any help.
function register_form($container)
{
....
....
/ Set Rules
$config = array(
...//for username
// for email
array(
'field'=>'email',
'label'=>$this->CI->lang->line('userlib_email'),
'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
),
...// for password
);
$this->CI->form_validation->set_rules($config);
The problem with creating a callback directly in the controller is that it is now accessible in the url by calling http://localhost/yourapp/yourcontroller/yourcallback which isn't desirable. There is a more modular approach that tucks your validation rules away into configuration files. I recommend:
Your controller:
<?php
class Your_Controller extends CI_Controller{
function submit_signup(){
$this->load->library('form_validation');
if(!$this->form_validation->run('submit_signup')){
//error
}
else{
$p = $this->input->post();
//insert $p into database....
}
}
}
application/config/form_validation.php:
<?php
$config = array
(
//this array key matches what you passed into run()
'submit_signup' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[255]|valid_email|belongstowork'
)
/*
,
array(
...
)
*/
)
//you would add more run() routines here, for separate form submissions.
);
application/libraries/MY_Form_validation.php:
<?php
class MY_Form_validation extends CI_Form_validation{
function __construct($config = array()){
parent::__construct($config);
}
function belongstowork($email){
$endsWith = "#mywork.com";
//see: http://stackoverflow.com/a/619725/568884
return substr_compare($endsWith, $email, -strlen($email), strlen($email)) === 0;
}
}
application/language/english/form_validation_lang.php:
Add: $lang['belongstowork'] = "Sorry, the email must belong to work.";
Are you need validation something like this in a Codeigniter callback function?
$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[254]|valid_email|xss_clean|callback_spare_email[' . $this->input->post('email') . ']');
if ($this->form_validation->run() == FALSE)
{
// failed
echo 'FAIL';
}
else
{
// success
echo 'GOOD';
}
function spare_email($str)
{
// if first_item and second_item are equal
if(stristr($str, '#mywork.com') !== FALSE)
{
// success
return $str;
}
else
{
// set error message
$this->form_validation->set_message('spare_email', 'No match');
// return fail
return FALSE;
}
}
A correction to Jordan's answer, the language file that you need to edit should be located in
system/language/english/form_validation_lang.php
not application/.../form_validation_lang.php. If you create the new file under the application path with the same name, it will overwrite the original in the system path. Thus you will lose all the usage of the original filters.

Categories