How to send an email with content from a View in codeigniter - codeigniter

I want to send an email to user from my application with the content of the email loaded from a view . This is the code i've tried out till now:
$toemail = "user#email.id";
$subject = "Mail Subject is here";
$mesg = $this->load->view('template/email');
$this->load->library('email');
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->to($toemail);
$this->email->from($fromemail, "Title");
$this->email->subject($subject);
$this->email->message($mesg);
$mail = $this->email->send();

You need to call $this->load->library('email'); within the controller as well for the email in CI to work.
Also , in your code : $fromemail is not initialized.
You need to have SMTP support on your server.
$config should be declared as an array before assigning values and keys.
Working Code:
$this->load->library('email');
$fromemail="ad#c.com";
$toemail = "user#email.id";
$subject = "Mail Subject is here";
$data=array();
// $mesg = $this->load->view('template/email',$data,true);
// or
$mesg = $this->load->view('template/email','',true);
$config=array(
'charset'=>'utf-8',
'wordwrap'=> TRUE,
'mailtype' => 'html'
);
$this->email->initialize($config);
$this->email->to($toemail);
$this->email->from($fromemail, "Title");
$this->email->subject($subject);
$this->email->message($mesg);
$mail = $this->email->send();
Edit:
$mesg = $this->load->view('template/email',true); should be having the true as pointed out by lycanian. By setting it as true , it doesn't send data to the output stream but it will return as a string.
Edit:
$this->load->view(); need a second parameter with data or empty like $mesg = $this->load->view(view,data,true);, if not it wont work

This line $mesg = $this->load->view('template/email',true); should be like this
$mesg = $this->load->view('template/email','',true);
with the single quotes before the value true, and it will work perfectly

Email template send In codeigniter we need to put and meta tag before sending email
$this->data['data'] = $data;
$message = $this->load->view('emailer/create-account', $this->data, TRUE);
$this->email->set_header('MIME-Version', '1.0; charset=utf-8');
$this->email->set_header('Content-type', 'text/html');
$this->email->from($email, $name);
$this->email->to('emailaddres#mail.com');
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();

U will try it!! it's working for mine after many errors facing
$subject = 'New message.';
$config = Array(
'protocol' => 'sendmail',
'smtp_host' => 'Your smtp host',
'smtp_port' => 465,
'smtp_user' => 'webmail',
'smtp_pass' => 'webmail pass',
'smtp_timeout' => '4',
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->set_header('MIME-Version', '1.0; charset=utf-8');
$this->email->set_header('Content-type', 'text/html');
$this->email->from('from mail address', 'Company name ');
$data = array(
'message'=> $this->input->post('message')
);
$this->email->to($toEmail);
$this->email->subject($subject);
$body = $this->load->view('email/sendmail.php',$data,TRUE);
$this->email->message($body);
$this->email->send();

Related

Codeigniter 3: send account activation email fails

I am working on a Register and Login application with CodeIgniter 3 and Twitter Bootstrap.
When a user registers, an email should be send to the address he/she provided, with an account confirmation link. The problem is that the confirmation email does not send.
In the Usermodel I have:
public function activationEmail($first_name='', $last_name='', $email='', $verification_key='')
{
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.code-love.tk',
'smtp_port' => 465,
'smtp_user' => 'razvan#code-love.tk',
'smtp_pass' => '******',
'smtp_crypto' => 'ssl',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$messg = 'Wellcome, '. $first_name . ' ' . $last_name . '! Click the <strong>confirmation link</strong> to confirm your account.';
$this->email->initialize($config);
$this->email->set_newline('\r\n');
$this->email->from('mail.code-love.tk','Razvan Zamfir');
$this->email->to($email);
$this->email->subject('Account activation');
$this->email->message($messg);
if (!$this->email->send()) {
show_error($this->email->print_debugger());
}
else {
echo 'Your e-mail has been sent!';
}
}
In my Signup controller I have this code:
public function signup() {
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
if ($this->form_validation->run()) {
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$password = $this->input->post('password');
$verification_key = md5($email);
$date_created = date('Y-m-d H:i:s');
$date_updated = date('Y-m-d H:i:s');
$active = 0;
// Load user model
$this->load->model('Usermodel');
// If email does not already exist in the database
// signup new user
if (!$this->Usermodel->email_exists($email)) {
if ($this->Usermodel->user_register($first_name, $last_name, $email, $password, $verification_key, $date_created, $date_updated, $active) && $this->Usermodel->activationEmail($first_name, $last_name, $email, $verification_key)) {
$this->session->set_flashdata("signup_success", "Your account has just bean created. You must confirm it before you can sign in. We have send you a confirmation email at $email for this purpose.");
} else {
// unless sigup does not fail for whatever reason
$this->session->set_flashdata("signup_failure", "We ware unable to create your account.");
}
redirect('signup');
} else {
// If email is already in the database
// urge user to sign in (redirect to signup page too)
$this->session->set_flashdata("email_exists", "The email address $email already exists in the database. Please signin.");
redirect('signin');
}
} else {
$this->load->view('signup');
}
}
The sign up does happen, with the error below, and the verification email is not send. I am not doing this from a local XAMPP/WAMP/MAMP server, but from a "live" one, you can signup yourself.
Severity: Warning
Message: fsockopen(): php_network_getaddresses: getaddrinfo failed: Name or service not known
Filename: libraries/Email.php
Line Number: 1950
Backtrace:
File: /home/roxoqdat/code-love.tk/ciauth/application/models/Usermodel.php
Line: 52
Function: send
File: /home/roxoqdat/code-love.tk/ciauth/application/controllers/Signup.php
Line: 42
Function: activationEmail
File: /home/roxoqdat/code-love.tk/ciauth/index.php
Line: 292
Function: require_once
What am I doing wrong?
Check if you have the required SMTP service.
Try with google SMTP service.
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx',
'smtp_pass' => 'xxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('mygmail#gmail.com', 'myname');
$this->email->to('target#gmail.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$result = $this->email->send();
Next try with:
$config = array('mailtype' => 'html');
Remove the rest from $config = array.
First of all, after setting flashdata, I don't see you redirecting the user to where they can see it...
Also, send the mail first, then you set flash data as An Activation Link Has Been Sent To Your Email, Please Check Your Email To Activate Your Account!
So,
User Registers,
An email is sent to them only if it doesn't exist already,
Set flashdata for any errors that may arise... Eg:
Assign a variable to the email sending function:
$send_email = $this->activationEmail('params');
In your activationEmail function, make sure there is a simple control structure like this:
$success=$this->email->send();
if($success){ return true; } else{ return false; }
Now in your controller, compare to see if mail is actually sent:
if($send_email == true){ $this->session->flashdata('success','Your success message');
// use the redirect() helper function to the function that loads your view
} else { //set failed flashdata and redirect to where you want it seen like above}
You then will know where the problem is.
Let the program flow in your mind first, then implement it. Try that first and get back to me right after.
Hope it somehow helps
Debug whether your parameters are passing or not (specially last_name). Try to write the model method like this to avoid showing errors
public function activationEmail($first_name='', $last_name='', $email='', $verification_key='')
Try adding header to your email (You are setting mailtype twice, might be an issue).
$this->email->set_header('MIME-Version', '1.0; charset=utf-8');
$this->email->set_header('Content-type', 'text/html');

Send email to create and attach PDF in CodeIgniter

The output email gets sent but does not arrive i my email. I have added dompdf library. When I removed the code that creates the pdf then the mail was sent.
My code:
<?php
$this->load->library('dompdf_gen');
$this->dompdf->load_html($body);
$this->dompdf->render();
$output = $this->dompdf->output(APPPATH . 'Brochure.pdf', 'F');
$email = $this->input->post('email');
$subject = "some text";
$message = $body;
$this->sendEmail($email, $subject, $message);
$config = Array(
'mailtype' => 'html'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('ul#ul.com');
$this->email->to($email);
$this->email->subject($subject);
$this->email->message($message);
$this->email->attach(APPPATH . 'Brochure.pdf');
if ($this->email->send())
{
echo 'Email send.';
}
else
{
show_error($this->email->print_debugger());
}
You must be save attachment as a file, so use file_put_contents to save pdf to a file. Set permission to 777 to accessible by public:
$this->load->library('dompdf_gen');
$this->dompdf->load_html($body);
$this->dompdf->render();
$output = $dompdf->output();
file_put_contents(APPPATH.'Brochure.pdf', $output);
chmod(APPPATH.'Brochure.pdf', 777);
$email=$this->input->post('email');
$subject="some text";
$message=$body;
$this->sendEmail($email,$subject,$message);
$config = Array(
'mailtype' => 'html' );
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('ul#ul.com');
$this->email->to($email);
$this->email->subject($subject);
$this->email->message($message);
$this->email->attach(APPPATH.'Brochure.pdf');
if($this->email->send())
{
echo 'Email send.';
}
else
{
show_error($this->email->print_debugger());
}
Use this library to convert html to pdf which I have modified for CI3.
https://github.com/shyamshingadiya/HTML2PDF-CI3
Please check below mentioned solution
//Load the library
$this->load->library('html2pdf');
//Set folder to save PDF to
$this->html2pdf->folder('./uploads/pdfs/');
//Set the filename to save/download as
$this->html2pdf->filename('new.pdf');
//Set the paper defaults
$this->html2pdf->paper('a4', 'portrait');
for Sending this particular file in email.
$this->load->library('email');
$this->email->from('your#example.com', 'Your Name');
$this->email->to('someone#example.com');
$this->email->subject('Email PDF Test');
$this->email->message('Testing the email a freshly created PDF');
$this->email->attach($path_to_pdf_file);
$this->email->send();
Let me know if it not work.

This is my codiegniter contact us form code , it's correct , but i want include mail functionality in this contact us form,

this code is working perfect for saving data into databse , but i just want to include mail functionality in this code.
Please take a look.
I have tried a lot, but in vain. Any help would be nice.
<?php
class contactform extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
}
function index()
{
//set validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required|callback_alpha_space_only');
$this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required');
$this->form_validation->set_rules('companyname', 'Companyname', 'trim|required');
//$this->form_validation->set_rules('industryname', 'Industryname', 'trim|required');
$this->form_validation->set_rules('country', 'Country', 'trim|required');
$this->form_validation->set_rules('message', 'Message', 'trim|required');
//run validation on post data
if ($this->form_validation->run() == FALSE)
{ //validation fails
$this->load->view('contact_form_view');
}
else
{
//insert the contact form data into database
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'subject' => $this->input->post('subject'),
'companyname' => $this->input->post('companyname'),
//'industryname' => $this->input->post('industryname'),
'country' => $this->input->post('country'),
'message' => $this->input->post('message')
);
if ($this->db->insert('contacts', $data))
{
// i just want a mailer
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">We received your message! Will get back to you shortly!!!</div>');
redirect('contactform/index');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Some Error. Please try again later!!!</div>');
redirect('contactform/index');
}
}
}
//custom callback to accept only alphabets and space input
function alpha_space_only($str)
{
if (!preg_match("/^[a-zA-Z ]+$/",$str))
{
$this->form_validation->set_message('alpha_space_only', 'The %s field must contain only alphabets and space');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
this code is working perfect , to save data in to database. Thanks in advance.
My mailer attempt is this
<?php
//configure email settings
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_user'] = 'user#gmail.com'; // email id
$config['smtp_pass'] = 'password'; // email password
$config['mailtype'] = 'html';
$config['wordwrap'] = TRUE;
$config['charset'] = 'iso-8859-1';
$config['newline'] = "\r\n"; //use double quotes here
$this->email->initialize($config);
?>
<?php
//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');
//set to_email id to which you want to receive mails
$to_email = 'user#gmail.com';
//send mail
$this->email->from($from_email, $name);
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
if ($this->email->send())
{
// mail sent
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">successfully!</div>');
redirect('contactform/index');
}
else
{
//error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center"> error </div>');
redirect('contactform/index');
}
?>
I am assuming that you want to send mail from localhost.To do this you can use PHPMailer library
$this->load->library('PHPMailer/PHPMailer');
//require("class.phpmailer.php");
$mail=new PHPMailer(); //creat PHPMailer object
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; //needs login information
$mail->SMTPSecure = "tls"; //specifies tls security
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; //gmail smtp port
/******************* Set Your Credentials********************/
$mail->Username ="user#gmail.com" ; //SMTP gmail address
$mail->Password = "password"; // SMTP account password
$mail->From = "fromxyz"; //sender's gmail address
$mail->isHTML(true);
$mail->FromName = "From name";
$mail->AddAddress($email);//receiver's e-mail address
$mail->Subject = "Email Subject";//e-mail subject
$mail->Body ="Email Message";//e-mail message
$mail->WordWrap = 50;
if(!$mail->send())
{
echo "error";
}
else
{
echo "successs";
}
If this also not work try making some changes in gmail account:
Login to gmail.
Go to My Account Section.
Then Go To Sign-in & Security > Connected apps & sites
In this section make Allow less secure apps: ON
in you Controller try this type
//run validation on post data
if ($this->form_validation->run() == FALSE)
{ //validation fails
$this->load->view('contact_form_view');
}
else
{
//insert the contact form data into database
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'subject' => $this->input->post('subject'),
'companyname' => $this->input->post('companyname'),
//'industryname' => $this->input->post('industryname'),
'country' => $this->input->post('country'),
'message' => $this->input->post('message')
);
//load email libary
$this->load->library('email');
//configure email settings
$config['protocol'] = 'smtp`';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_user'] = 'user#gmail.com'; // email id
$config['smtp_pass'] = 'password'; // email password
$config['mailtype'] = 'html';
$config['wordwrap'] = TRUE;
$config['charset'] = 'iso-8859-1';
$config['newline'] = "\r\n"; //use double quotes here
$this->email->initialize($config);
//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');
//set to_email id to which you want to receive mails
$to_email = 'user#gmail.com';
//send mail
$this->email->from($from_email, $name);
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
if ($this->email->send())
{
// mail sent
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">successfully!</div>');
}
else
{
//error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center"> error </div>');
}
}

Email Attachment not working in codeigniter

Mail function with attachment file is not working in codeigniter, i m not receiving any mail with attachment.. before i received the mail without attachment but after i used "$_SERVER["DOCUMENT_ROOT"]."/admin/assets/image/order_complete_file/".$image_name;", i didnt receive any mail.. kindly help me.. Here my coding is
$image_name = "some_name";
$content = "some content";
$subject = "Subject Name";
$this->load->helper('email');
$this->load->library('email');
$this->email->set_newline("\r\n");
$this->email->from('abc#gmail.com');
$this->email->to('xxx#gmail.com');
$this->email->subject($subject);
$this->email->message($content);
$attched_file = $_SERVER["DOCUMENT_ROOT"]."/admin/assets/image/order_complete_file/".$image_name;
$this->email->attach($attched_file);
$this->email->send();
You should use config parameter for email library, and set 'mailtype' to 'html'(Default Value is 'text'). If it still fails, you should use the print_debugger() function to see why.
$config = Array(
'mailtype' => 'html'
);
$image_name = "some_name";
$content = "some content";
$subject = "Subject Name";
$this->load->library('email');
$this->email->initialize($config);
$this->email->from('abc#gmail.com');
$this->email->to('xxx#gmail.com');
$this->email->subject($subject);
$this->email->message($content);
$attched_file = $_SERVER["DOCUMENT_ROOT"]."/admin/assets/image/order_complete_file/".$image_name;
$this->email->attach($attched_file);
if($this->email->send()){ echo 'Email send.';}
else {show_error($this->email->print_debugger()); }

how to send email using codeigniter

today i have sending email using code igniter but not work properly .so please any one help me.
this is my controller page code here;
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {enter code here
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
// $this->load->library('pagination');
$this->load->library('session','form_validation');
}
function sendMail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'siva#gmail.com', // here goes your mail
'smtp_pass' => 'mygamilpassword', // here goes your mail password
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->email->initialize($config);
$message = 'hiiiiii';
$this->load->library('email', $config);
$this->email->set_newline("rn");
$this->email->from('siva#gmail.com'); // here goes your mail
$this->email->to('sam#gmail.com');// here goes your mail
$this->email->subject('Resume from JobsBuddy');
$this->email->message($message);
if($this->email->send())
{
echo 'Email sent.';
}
else
{
show_error($this->email->print_debugger());
}
} $this->sendMail;
}
and in my localhost open php.extension->php.openssl enable and also the port number change for 465, and smtp:smtp.gmail.com this are all enable it.
but not working help me.?
Try this code. This is the working code:
function sendMail()
{
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.googlemail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "siva#gmail.com";
$config['smtp_pass'] = "mygamilpassword";
$message = "Your email body text goes here";
$config['mailtype'] = "html";
$ci = & get_instance();
$ci->load->library('email', $config);
$ci->email->set_newline("\r\n");
$ci->email->from("siva#gmail.com");
$ci->email->to("siva#gmail.com");
$ci->email->subject("Resume from JobsBuddy");
$ci->email->message($message);
$ci->email->send();
echo $this->email->print_debugger();
}
Try this code. This is the working code and allow-less-secure-apps-access-gmail-account setting open
public function send_mail() {
ini_set('SMTP', "server.com");
ini_set('smtp_port', "25");
ini_set('sendmail_from', "yourmail#gmail.com");
$this->load->library('email');
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'yourmail#gmail.com';
$config['smtp_pass'] = 'yourpassword';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'text'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$this->email->initialize($config);
$this->email->set_newline("\r\n");
$from_email = "frommailid#gmail.com";
$to_email = "tomailid#gmail.com";
//Load email library
$this->load->library('email');
$this->email->from($from_email, 'Identification');
$this->email->to($to_email);
$this->email->subject('Send Email Codeigniter');
$this->email->message('The email send using codeigniter library');
//Send mail
if($this->email->send())
$this->session->set_flashdata("email_sent","Congragulation Email Send Successfully.");
else
show_error($this->email->print_debugger());
$this->session->set_flashdata("email_sent","You have encountered an error");
$this->load->view('contact_email_form');
}

Resources