Codeigniter 3 applcation bug: unable to send valid link via email message - php

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.
I have added a registration and login system to this application. I am current working on a password reset system.
I was able to do these 2 things separately:
Send a password reset email containing dummy text.
Create a valid password reset link.
I was unable however, to send the email once the reset link was inserted into the email body.
Here is he controller:
class Newpassword extends CI_Controller {
public function __construct()
{
parent::__construct();
}
private $sender_email = "noreply#yourdomain.com";
private $sender_name = "Razvan Zamfir";
private $user_email = '';
private $subject = 'Pasword reset link';
private $reset_token = '';
private $reset_url = '';
private $reset_link = '';
private $body = '';
public function index() {
// Display form
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'Reset your password';
$data['categories'] = $this->Categories_model->get_categories();
// Form validation rules
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if(!$this->form_validation->run()) {
$this->load->view('partials/header', $data);
$this->load->view('auth/passwordreset');
$this->load->view('partials/footer');
} else {
if ($this->Usermodel->email_exists()) {
//Get user email
$this->user_email = $this->input->post('email');
//create token
$this->reset_token = md5(str_shuffle($this->user_email));
//create url
$this->reset_url = base_url('changepasword/') . $this->user_email . '/'. $this->reset_token;
//create reset link
$this->reset_link = 'password reset link';
echo $this->reset_link;die();
$this->body = "Here is your $this->reset_link. \n\nAfter clicking it you will be redirected to a page on the website where you will be able to set a new pasword.";
// Send mail and rediect
$this->sendResetMail();
} else {
$this->session->set_flashdata('email_non_existent', "The email you provided does not exist in our database");
}
redirect('newpassword');
}
}
public function sendResetMail() {
// Loading the Email library
$config['protocol'] = 'sendmail';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
if(!$this->load->is_loaded('email')){
$this->load->library('email', $config);
} else {
$this->email->initialize($config);
}
// Build the body and meta data of the email message
$this->email->from($this->sender_email, $this->sender_name);
$this->email->to($this->user_email);
$this->email->subject($this->subject);
$this->email->message($this->body);
if($this->email->send()){
$this->session->set_flashdata('reset_mail_confirm', "A pasword reset link was send to the email address $this->user_email");
} else{
$this->session->set_flashdata('reset_mail_fail', "Our atempt to send a pasword reset link to $this->user_email has failed");
}
}
}
I have inspected the link, it is valid and the value of the href attribute is as intended, but once I remove echo $this->reset_link;die() I see the attempt to send the email failing:
Where is my mistake?

The email not sending issue can be from multiple reasons:
Codeigniter 3 email library is not configured correctly
test: use built in email() in php and test if that's working
php not configured correctly to send email
server is not configured for handing over emails
DNS has external mx records and local email is not forwarded out from the server
test: use external SMTP server (free gmail is fine) and configure like this the ci3 library https://forum.codeigniter.com/thread-75525-post-371979.html#pid371979
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = 'your_email';
$config['smtp_pass'] = 'your_password';
$config['smtp_port'] = 465;
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['newline'] = "\r\n";
if this is not working, check what's the cause by using
if ($this->email->send(FALSE))
{
echo $this->email->print_debugger();
}
server cannot access remote ports firewalls are not opened for this
test: disable firewall or selinux and test again

Are you running it locally? If so this might be the cause of the error. Can't send emails from local machines. If not check with your hosting company if it allows you to send mails via php. Most shared hostings disable this option and sell SMTP service to allow you to send emails

Have you tried loading a view into your email function? Then you could pass the content to that file and send a html email

This is what woked for me:
public function sendResetMail()
{
// Email settings
$config['protocol'] = 'sendmail';
$config['smtp_host'] = 'mail.mydomain.com';
$config['smtp_user'] = 'myemail#mydomain.com';
$config['smtp_pass'] = '******';
$config['smtp_port'] = 465;
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['newline'] = "\r\n";
if (!$this->load->is_loaded('email')) {
$this->load->library('email', $config);
} else {
$this->email->initialize($config);
}
// Build the body and meta data of the email message
$this->email->from($this->sender_email, $this->sender_name);
$this->email->to($this->user_email);
$this->email->subject($this->subject);
$this->email->message($this->body);
if ($this->email->send()) {
$this->session->set_flashdata('reset_mail_confirm', "A pasword reset link was send to the email address $this->user_email");
} else {
$this->session->set_flashdata('reset_mail_fail', "Our atempt to send a pasword reset link to $this->user_email has failed");
}
}

Related

Passing data from one view to email template view on checkbox checked in code-igniter

I'm using a code-igniter to develop an web application. I'm trying to create a dynamic email template which loads data dynamically when I'm check a checkbox from other view.
Here is my scenario:
If I'm checking a checkbox for HMO_001, then all data that will loaded in the table for HMO_001 will pass to my email template, and when I'm click on Send button the mail will send to particular landlord.
Now I'm able to send an email to multiple landlords at a time on button click when I'm check multiple checkbox, but the email is hard coded. I'm trying to make it dynamic, but no success.
Here is my Code:
Controller to load table data:
public function index()
{
# code...
$user = $this->ion_auth->user()->row();
$data['username'] = $user->username;
$data['user_id'] = $user->id;
$landlord = $this->input->post('landlord_id');
$property = $this->input->post('property_id');
$certificate = $this->input->post('certificate_id');
if( $landlord =='') {
$landlord = 0;
}
if($property == ''){
$property = 0;
}
if($certificate == ''){
$certificate = 0;
}
$data['landlords'] = $this->c->landlordList();
//$data['properties'] = $this->c->propertyList();
$data['certificates'] = $this->c->certificateList();
//$data['certified'] = $this->c->certificate_List();
$data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);
// print_r($data['landlords']);
// print_r($data['properties']);
// echo "<pre>";
// print_r($data['certificates']);
// echo "</pre>";
// exit();
$data['title'] = 'Certificate List';
$this->load->view('template/header', $data);
$this->load->view('certificate/certificate_list', $data);
$this->load->view('template/footer');
}
Controller to send mail:
public function sendMail()
{
# code...
//$data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['sendMail'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['sendMail'] as $selected){
//echo $selected."</br>";
}
}
}
$email_to = $this->input->post('sendMail[]');
<!-- echo "<pre>";
print_r($email_to);
echo "</pre>";
exit(); -->
$body = $this->load->view('emailTemplate/certTemplate', $data);
$this->load->library('email');
$config = array();
$config['protocol'] = 'mail';
$config['smtp_port'] = 587;
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = 'info#admin.com';
$config['smtp_pass'] = '**********';
$config['smtp_crypto'] = 'STARTTLS';
$config['newline'] = "\r\n"; //REQUIRED! Notice the double quotes!
$config['crlf'] = "\r\n";
$config['mailtype'] = "html";
$this->email->initialize($config);
$this->email->from('info#admin.com', 'Administrator');
$this->email->to($email_to);
$this->email->subject('Your Subject');
$this->email->message('$body');
$sent = $this->email->send();
if ($sent)
{
echo 'OK, mail send successfully';
} else {
echo $this->email->print_debugger();
}
}
Any kind of help is welcome, Thanks in advance.
To make a customized email message template, you could do like it this :
1. Move each recipient part to foreach loops that you've made prevously, this way you know each of email to recipient that is not being sent.
2. Add a third TRUE parameter on message $body (to return data as a string & not sending it to browser).
3. Add clear() method so each recipient only receive their customized message (to prevent showing all recipients on each recipient).
public function sendMail()
{
# code...
//$data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['sendMail'])){
$this->load->library('email');
$config = array();
$config['protocol'] = 'mail';
$config['smtp_port'] = 587;
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = 'info#admin.com';
$config['smtp_pass'] = '**********';
$config['smtp_crypto'] = 'STARTTLS';
$config['newline'] = "\r\n"; //REQUIRED! Notice the double quotes!
$config['crlf'] = "\r\n";
$config['mailtype'] = "html";
$this->email->initialize($config);
// Loop to store and display values of individual checked checkbox.
foreach($_POST['sendMail'] as $selected){
$data['email_to'] = $selected;
$body = $this->load->view('emailTemplate/certTemplate', $data, TRUE); // the TRUE parameter will return data as a string instead of sending it to browser (access recipient email on certTemplate with $email_to variable)
$this->email->clear();
$this->email->from('info#admin.com', 'Administrator');
$this->email->to($email_to);
$this->email->subject('Your Subject');
$this->email->message($body); // remove quotes from $body
$sent = $this->email->send();
if ($sent)
{
echo 'OK, mail send successfully';
} else {
echo $this->email->print_debugger();
}
}
}
}
}
Hope it helps..

Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method

Iam using codeigniter
I exicuted the code on live server.
got the following error using print_debugger()
Unable to send email using PHP SMTP. Your server might not be
configured to send mail using this method.
public function sendEnquiry() {
$this->load->library('email');
$name = $this->input->post("fname");
$cemail = $this->input->post("email");
$pno = $this->input->post("phone");
$message = $this->input->post("message");
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://mail.gatewaykhobar.com';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = '***********';
$config['smtp_pass'] = '***********';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'text'; // or html
$config['validation'] = FALSE;
$this->email->initialize($config);
$this->email->from('info#gatewaykhobar.com','Gateway Restaurent Contact');
$this->email->to($cemail);
$this->email->subject('Gateway Restaurent Contact Enquiry');
$this->email->message($message);
$send = $this->email->send();
if($send) {
echo json_encode("send");
} else {
$error = $this->email->print_debugger(array('headers'));
echo json_encode($error);
}
}
Change smtp_port from 465 to 587.
Make sure $config['newline'] = "\r\n"; is in double quotes not single quotes.
$mail_config['smtp_host'] = 'smtp.gmail.com';
$mail_config['smtp_port'] = '587';
$mail_config['smtp_user'] = 'user#example.com';
$mail_config['_smtp_auth'] = TRUE;
$mail_config['smtp_pass'] = 'password';
$mail_config['smtp_crypto'] = 'tls';
$mail_config['protocol'] = 'smtp';
$mail_config['mailtype'] = 'html';
$mail_config['send_multipart'] = FALSE;
$mail_config['charset'] = 'utf-8';
$mail_config['wordwrap'] = TRUE;
$this->email->initialize($mail_config);
$this->email->set_newline("\r\n");
I just added the last line
A common cause of this is the way that CodeIgniter interacts with the SMTP server with regards to line breaks. Your SMTP server might require \r\n and CodeIgniter is using \n.
There is an easy fix: after your $this->email->initialize(), add the following:
$this->email->set_newline("\r\n");
That should get it working for you.
Just use "mail" for the 'protocol' array item, and that's all...
$config = array();
$config['useragent'] = $system_name;
$config['mailpath'] = "/usr/bin/sendmail"; // or "/usr/sbin/sendmail"
$config['protocol'] = "mail"; //use 'mail' instead of 'sendmail or smtp'
$config['smtp_host'] = "your domain name";
$config['smtp_user'] = $from;
$config['smtp_pass'] = "*************";
$config['smtp_port'] = 465;
$config['smtp_crypto'] = 'ssl';
$config['smtp_timeout'] = "";
$config['mailtype'] = "html";
$config['charset'] = "utf-8";
$config['newline'] = "\r\n";
$config['wordwrap'] = TRUE;
$config['validate'] = FALSE;
It looks like the mail server is hosted by yourself as well, try sending email from any e-mail client. If it fails - there's a problem with your mailserver config, not the code you pasted - check the server logs.
I am using much time Run my configure code in localhost but it always gives me an error (Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.)
But when run this Below code in my server it works for me.
application>controller>Sendingemail_Controller.php
public function send_mail() {
$this->load->library('email');
$config = array();
$config['protocol'] = "smtp"; // you can use 'mail' instead of 'sendmail or smtp'
$config['smtp_host'] = "ssl://smtp.googlemail.com";// you can use 'smtp.googlemail.com' or 'smtp.gmail.com' instead of 'ssl://smtp.googlemail.com'
$config['smtp_user'] = "my#gmail.com"; // client email gmail id
$config['smtp_pass'] = "******"; // client password
$config['smtp_port'] = 465;
$config['smtp_crypto'] = 'ssl';
$config['smtp_timeout'] = "";
$config['mailtype'] = "html";
$config['charset'] = "iso-8859-1";
$config['newline'] = "\r\n";
$config['wordwrap'] = TRUE;
$config['validate'] = FALSE;
$this->load->library('email', $config); // intializing email library, whitch is defiend in system
$this->email->set_newline("\r\n"); // comuplsory line attechment because codeIgniter interacts with the SMTP server with regards to line break
$from_email = $this->input->post('f_email'); // sender email, coming from my view page
$to_email = $this->input->post('email'); // reciever email, coming from my view page
//Load email library
$this->email->from($from_email);
$this->email->to($to_email);
$this->email->subject('Send Email Codeigniter');
$this->email->message('The email send using codeigniter library'); // we can use html tag also beacause use $config['mailtype'] = 'HTML'
//Send mail
if($this->email->send()){
$this->session->set_flashdata("email_sent","Congragulation Email Send Successfully.");
echo "email_sent";
}
else{
echo "email_not_sent";
echo $this->email->print_debugger(); // If any error come, its run
}
}
and my view page where I defined f_email and email comes through post method.
application>view>emailtesting.php
<html>
<head>
<title> Send Email Codeigniter </title>
</head>
<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Sendingemail_Controller/send_mail');
?>
<input type = "email" name = "f_email" placeholder="sender email id (from)" required />
<input type = "email" name = "email" placeholder="reciever email id (to)" required />
<input type = "submit" value = "SEND MAIL">
<?php
echo form_close();
?>
</body>
if some error comes again please visit official documentation below:
https://codeigniter.com/user_guide/libraries/email.html
For anyone else who finds this error, has set the settings mentioned elsewhere (even Codeigniter 4) but still getting tht error, one way to test what is going on is from the server console and using telnet. For example:
telnet smtp.yourprovider.com 587
Then test against a different provider and see if that works. If your provider doesn't but another does then the problem is with your provider and you should contact them. If both can't connect then you should speak with your webhost.
I've found another solution. I had the same problem: (Codeigniter 4 and the issue with php smtp), and the reason was 2-step verification of my gmail account, from which I wanted to send emails in my app. I fixed it by getting from my gmail account, password for my app. It works, at last.

Mail not sending/ delever php codeigniter

I am trying to send forgot password link to gmail. but can't get success.
Here is my little code. I have my config file here. If any changes needed then please suggest. I am using two gmail account to send mail from one gmail account to other gmail account.
Here is my config file email.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = Array(
$config['protocol'] = 'smtp',
$config['smtp_host'] = 'ssl://smtp.gmail.com',
$config['smtp_port'] = '465',
$config['smtp_timeout'] = '7',
$config['smtp_user'] = 'xyz#gmail.com',
$config['smtp_pass'] = '123',
$config['charset'] = 'utf-8',
$config['newline'] = "\r\n",
$config['mailtype'] = 'text', // or html
$config['validation'] = TRUE // bool whether to validate email or not
);
Here is my code for deliver mail.
if($this->form_validation->run())
{
//echo 1;
//echo validation_errors();
$this->load->library('email');
$reset_key = md5(uniqid());
$this->load->model('User_Model');
if($this->User_Model->update_reset_key($reset_key))
{
$this->email->from('xyz#gmail.com', 'data-+-');
$this->email->to($this->input->post('email'));
$this->email->subject('Reset you account password at Mahesh Makwana');
$message = "<p><h4>You or someone request to reset your password.</h4></p>";
$message.="<a href='".base_url(). "reset_password/".$reset_key."'>Click here to reset your password</a>";
$this->email->message($message);
if($this->email->send())
{
echo 'Kindly check your email '.$this->input->post('email').' to reset your password';
}
else
{
echo 'Cannot send email! Kindly contact to our customer service to help you.!';
}
}
else{
echo 1;
}
}
else
{
//echo 0;
//echo validation_errors();
$this->load->view('include/forgetpassword');
}
Nothing wrong in your code. Its might be because of google security. Try to allow access for 'Less secure apps' in google account settings after logging in to your account
https://www.google.com/settings/security/lesssecureapps
Manage your configuration setting like below:
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'xyz#gmail.com';
$config['smtp_pass'] = 'xxxxx';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'text' // or html
$config['validation'] = TRUE; // bool whether to validate email or not
Then after loading email library set configuration using $this->email->initialize($config);
$this->load->library('email');
$this->email->initialize($config);

Php mailer in codeigniter

i want to send a email when register a user. i'm using the xampp, codeigniter and phpMailer. when i submit the registration form it was an error called
Message was not sent
PHPMailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Registration Successfully !
here is my code(controller)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to start session in order to access it through CI
//The controller class is extends CI_Contoller
Class User_Authentication extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
$this->load->library('my_phpmailer');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('login_database');
}
// Show login page
public function index() {
$this->load->view('user_site/login_form');
}
// Show registration page
public function user_registration_show() {
$this->load->view('user_site/registration_form');
}
// Validate and store registration data in database
public function new_user_registration() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|md5');
if ($this->form_validation->run() == FALSE) {
$this->load->view('user_site/registration_form');
// $this->load->view('register');
} else {
$data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'address' => $this->input->post('address'),
'contact_no' => $this->input->post('contact_no')
);
$result = $this->login_database->registration_insert($data);
if ($result == TRUE) {
$data['message_display'] = 'Registration Successfully !';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
// or try these settings (worked on XAMPP and WAMP):
// $mail->Port = 587;
// $mail->SMTPSecure = 'tls';
$mail->Username = "ashik#gmail.com";
$mail->Password = "zswedfr";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true; // if you want to send a same email to multiple users. multiple emails will be sent one-by-one.
$mail->From = "ashik#gmail.com";
$mail->FromName = "ABC";
$address = $_POST['email'];
$mail->AddAddress($address, "Guest");
$mail->Subject = "ABC Email validation ";
$mail->Body ="ABC Email validation";
if(!$mail->Send()){
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
}else{
echo "sucfdt " ;
}
$this->load->view('user_site/login_form', $data);
} else {
$data['message_display'] = 'Email already exist!';
//$this->load->view('user_site/registration_form', $data);
$this->load->view('register');
}
}
}
this is the php file in library
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_PHPMailer {
public function My_PHPMailer() {
require_once('PHPMailer/PHPMailerAutoload.php');
}
}
This code give the error that authentication failure in gmail server. It is because, gmail is assuming that the login computer/location is changed, and so it is auspicious. If you login to your gmail and look in security, recently logged devices, you can see a popup showing that login blocked from your server address. Check your access status here
If you enable it, this will work. Go to this link for unlocking
see this below thread. You can refer this too.
PHPMailer - SMTP ERROR: Password command failed when send mail from my server
Make a file email.php in application/config/ folder :
And these contents into it :
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com'; //change this
$config['smtp_port'] = '465';
$config['smtp_user'] = ''; //change this
$config['smtp_pass'] = ''; //change this
$config['mailtype'] = 'html';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n";

Codeigniter $this->email->send() not working while mail() does

I can't figure out why if I try to use the CI Email Class it doesn't send emails, while if I use the native PHP mail() Class works.
Has to be noted that sometimes I get "email sent" while is not actually sent and sometimes I get the error "my server is not setup".
I tried to figure out how to set it up but... nothing...
Controller code follows:
if($this->form_validation->run()){
//Set Language
$this->lang->load('site', $this->session->userdata('lang'));
//Random key
$user_valid_key = md5(uniqid());
//Prepare email
$this->load->library('email', array('mailtype' => 'html'));
$this->email->from($this->config->item('email_signup_from'), 'Wondermark.net');
$this->email->to($this->input->post('email'));
$this->email->subject($this->lang->line('email_signup_subject'));
//Format mail con %s per inserire i campi necessari
$signup_msg = sprintf($this->lang->line('email_signup_message'), $this->input->post('fname'), base_url().'main/signup_confirm/'.$user_valid_key);
$this->email->message((string)$signup_msg);
if($this->email->send()){
//TODO: load view...
echo "email sent";
}else{
$to = $this->input->post('email');
mail($to, 'test', 'Other sent option failed');
echo $this->input->post('email');
show_error($this->email->print_debugger());
}
//TODO: Add to db
}else{
// Form validation failed
}
Use this setup 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'] = 'sender_mailid#gmail.com';
$config['smtp_pass'] = 'password';
$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->from('sender_mailid#gmail.com', 'sender_name');
$this->email->to('recipient#gmail.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
echo $this->email->print_debugger();
I faced this problem and found the following solution. Just a little change in the email config and it's working 100%:
$config['protocol'] = 'ssmtp';
$config['smtp_host'] = 'ssl://ssmtp.gmail.com';
Codeigniter User Guide: https://www.codeigniter.com/user_guide/libraries/email.html
This setup works for me:
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'Your SMTP Server',
'smtp_port' => 25,
'smtp_user' => 'Your SMTP User',
'smtp_pass' => 'Your SMTP Pass',
'mailtype' => 'html'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
//Add file directory if you need to attach a file
$this->email->attach($file_dir_name);
$this->email->from('Sending Email', 'Sending Name');
$this->email->to('Recieving Email address');
$this->email->subject('Email Subject');
$this->email->message('Email Message');
if($this->email->send()){
//Success email Sent
echo $this->email->print_debugger();
}else{
//Email Failed To Send
echo $this->email->print_debugger();
}
I am using much time Run my configure code in localhost but it always gives me an error (Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.)
But when run this Below code in my server it works for me.
application>controller>Sendingemail_Controller.php
public function send_mail() {
$this->load->library('email');
$config = array();
$config['protocol'] = "smtp"; // you can use 'mail' instead of 'sendmail or smtp'
$config['smtp_host'] = "ssl://smtp.googlemail.com";// you can use 'smtp.googlemail.com' or 'smtp.gmail.com' instead of 'ssl://smtp.googlemail.com'
$config['smtp_user'] = "my#gmail.com"; // client email gmail id
$config['smtp_pass'] = "******"; // client password
$config['smtp_port'] = 465;
$config['smtp_crypto'] = 'ssl';
$config['smtp_timeout'] = "";
$config['mailtype'] = "html";
$config['charset'] = "iso-8859-1";
$config['newline'] = "\r\n";
$config['wordwrap'] = TRUE;
$config['validate'] = FALSE;
$this->load->library('email', $config); // intializing email library, whitch is defiend in system
$this->email->set_newline("\r\n"); // comuplsory line attechment because codeIgniter interacts with the SMTP server with regards to line break
$from_email = $this->input->post('f_email'); // sender email, coming from my view page
$to_email = $this->input->post('email'); // reciever email, coming from my view page
//Load email library
$this->email->from($from_email);
$this->email->to($to_email);
$this->email->subject('Send Email Codeigniter');
$this->email->message('The email send using codeigniter library'); // we can use html tag also beacause use $config['mailtype'] = 'HTML'
//Send mail
if($this->email->send()){
$this->session->set_flashdata("email_sent","Congragulation Email Send Successfully.");
echo "email_sent";
}
else{
echo "email_not_sent";
echo $this->email->print_debugger(); // If any error come, its run
}
}
and my view page where I defined f_email and email comes through post method.
application>view>emailtesting.php
<html>
<head>
<title> Send Email Codeigniter </title>
</head>
<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Sendingemail_Controller/send_mail');
?>
<input type = "email" name = "f_email" placeholder="sender email id (from)" required />
<input type = "email" name = "email" placeholder="reciever email id (to)" required />
<input type = "submit" value = "SEND MAIL">
<?php
echo form_close();
?>
</body>
if some error comes again please visit official documentation below:
https://codeigniter.com/user_guide/libraries/email.html
After fighting with this same problem for a couple hours I finally decided to change my config to send through a different server. My original server for some reason would send to some addresses but not others (in same domain). As soon as I changed to sendgrid it worked as expected.
If you are not getting the results you expect, try a different smtp server. The problem may not be your code...
I had the same problem and I try below code instead of Codeignitor's mail function.
mail('mypersonalmail#domainserver.com' , 'Test', 'Test Email');
It works and mail is send to the email address. That mail has sent by already created email address (As i think). In my case it is:
gtt28651ff#p3plcpnl0552.srod.ahx3.domainserver.com
So I copy this email address and try it with below code.
$this->email->from('gtt28651ff#p3plcpnl0552.srod.ahx3.domainserver.com', 'www.domainserver.com');
And it work fine. It seems to be some servers need already created email address to send the email while others are NOT.
Hope this is clear and helpful.
Lately, sending emails through Google SMTP can be very tricky due to their security checks.
Verify if:
you have the rDNS on your server and it's matching your server IP
disable the 2-step auth on the email you are using to send emails from (on Google settings)
have IMAP and POP enabled on the email you are using to send emails from (on Google settings)
allow less secure apps on the email you are using to send emails from (on Google settings)
Change the CI settings as follows:
//Google settings for CI
$config['protocol'] = 'ssmtp'; //smtp not working
$config['smtp_host'] = 'ssl://ssmtp.gmail.com'; //notice ssmtp
$config['smtp_user'] = 'anyemail#server.com'; //must use Google
$config['smtp_pass'] = '***********';
$config['smtp_port'] = '465';
$config['smtp_crypto'] = 'ssl';
//general settings
$config['_smtp_auth'] = TRUE; //important
$config['smtp_timeout'] = 30;
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
//optional
$config['wrapchars'] = 76;
$config['wordwrap'] = TRUE;
I hope this will save you the 2 days I have struggled with this issue.
I've spent hours trying to change the port,enabling the ssl extension in php.ini file etc nothing worked only ended up in a message SMTP server is not configured properly.I use WAMP as a localhost,when i turn off my antivirus avast the same config worked!!! the was send successfully.so it may be your antivirus program blocking on a local machine.

Categories