CI SMTP gmail sending - php

email is getting send at local but giving error when site uploaded
here is code of library please help
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Emaillib {
function send_email($fromEmail, $fromName, $details) {
$CI = & get_instance();
$CI->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'abc#gmail.com'; // Email
$config['smtp_pass'] = '*****'; // Password
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'html'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$CI->email->initialize($config);
$CI->email->from($fromEmail, $fromName);
$CI->email->to('abc#xyz.com'); // To Email
$CI->email->reply_to($fromEmail, $fromName);
$CI->email->subject('Enquiry through Website');
$CI->email->message($details);
$isSent = $CI->email->send();
//echo $CI->email->print_debugger();
if (!$isSent) {
return 'false';
}
return 'success';
}
}
?>

Because you said that it works fine locally it indicates that it is a problem with the code but rather with the server configuration. It's hard to say what the exact issue is but I would do the following
Check the server log files for any errors
Make sure the you have enabled SSL in your php.ini by check that the following line is - uncommented extension=php_openssl.dll
Make sure that port 465 is open
Try those to start with and see what happens

Related

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);

Sending email over Office365 account in Codeigniter 3 - connection timeout

I'm trying to connect to my Office365 account and send out an email in Codeigniter 3:
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = '****';
$config['smtp_pass'] = '****';
$config['smtp_port'] = '587';
$config['smtp_timeout'] = '60';
$config['smtp_crypto'] = 'tls';
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('****', '****');
$this->email->to('****');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send(FALSE);
$this->email->print_debugger();
This code works fine on my local server (wamp), but not on my production server (Debian), that's why I suspect some settings on the server need to be altered. All I get is this:
A PHP Error was encountered
Severity: Warning
Message: fsockopen(): unable to connect to smtp.office365.com:587 (Connection timed out)
Filename: libraries/Email.php
Line Number: 1949
I also tried sending mail with Phpmailer class and I got the same result; works on my local machine, not on production server.
Codeigniter class uses function fsockopen to connect to the mail server, but I can't find out the solution, since I don't know much about server configuration.
Any suggestion would be appreciated!
Here is what has worked for me in the past:
<?php
$config['smtp_crypto'] = 'tls';
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = 'USER#EMAIL.COM';
$config['smtp_pass'] = 'password';
$config['smtp_port'] = '587';
$config['charset']='utf-8'; // Default should be utf-8 (this should be a text field)
$config['newline']="\r\n"; //"\r\n" or "\n" or "\r". DEFAULT should be "\r\n"
$config['crlf'] = "\r\n"; //"\r\n" or "\n" or "\r" DEFAULT should be "\r\n"
?>
Also to note that the FROM address must be the same as smtp_user
You probably ran php on a Linux machine, if this is the case, you'd need to use following line to override CodeIgniter's configuration parameter
'newline' => "\r\n", //must have for office365!
I published an article here:
http://aus800.com.au/sending-out-emails-using-codeigniter-from-office365-account/
I cant exactly point out the error. So i posted 3 Methods. Grab the Idea or which Method is worked out.
Method 01
Login in to the Microsoft Online Services Portal.
Click on Outlook
Click Options (upper right corner)
Click on About
There will be a section titled External SMTP setting that looks like:
The important information is:
Server name: pod51010.outlook.com (your’s may be different)
Port: 587
Encryption method: TLS
then
$config['smtp_host'] = '';//change this
$config['smtp_timeout'] = '5';//fist try with 5 if no response increase to 90 and check
Method 02
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.office365.com';
$config['smtp_user'] = '****';
$config['smtp_pass'] = '****';
$config['smtp_port'] = '465';//change this
$config['smtp_timeout'] = '60';
$config['smtp_crypto'] = 'tls';
SSL/TLS vs plaintext/STARTTLS port numbers
Method 03
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'tls://smtp.office365.com';//change this
$config['smtp_user'] = '****';
$config['smtp_pass'] = '****';
$config['smtp_port'] = '587';
$config['smtp_timeout'] = '60';
$config['smtp_crypto'] = 'tls';//not sure about this, if not work remove this and try once
continue with this tested code
<?php
$mail= new phpmailer();
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'alertas#xxx.com';
$mail->Password = 'Password';
$mail->SetFrom('alertas#xxx.com', 'FromEmail'`enter code here`);
$mail->addAddress('x#xxx.com', 'ToEmail');
$mail->IsHTML(true);
$mail->Subject = 'Correo desde PHP';
$mail->Body = 'Prueba de correo desde php</b>';
if(!$mail->send()) {
echo "Ok";
} else {
echo "Error";
}
?>
For those facing same problem to connect Office365 smtp on 2019 and after:
I resolved my problem just using PHPMailer Class.
I tested everything here and in another questions and nothing.
Uploaded PHPMailer Folder, set up config files and boom. Emails works.
Using codeigniter 3.10 and problem seems to remain since this is a old question.
In their Email class (codeigniter) have a comment that seems smtp connect is not very good...
/**
* STREAM_CRYPTO_METHOD_TLS_CLIENT is quite the mess ...
*
* - On PHP <5.6 it doesn't even mean TLS, but SSL 2.0, and there's no option to use actual TLS
* - On PHP 5.6.0-5.6.6, >=7.2 it means negotiation with any of TLS 1.0, 1.1, 1.2
* - On PHP 5.6.7-7.1.* it means only TLS 1.0
*
* We want the negotiation, so we'll force it below ...
*/
I don't speak english very well but this seems little confusing.
Ok, so, if you don't want to lose more time, upload PHPMailer Folder you can download at:
https://github.com/PHPMailer/PHPMailer
Upload your PHPMailer folder to application/libraries/ and create a file there too:
MY_phpmailer.php
In MY_phpmailer.php file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_PHPMailer {
public function My_PHPMailer() {
require_once('Phpmailer/class.phpmailer.php');
}
}
?>
PHPMailer send function:
public function sendmail2($to,$subject,$message,$reply=null,$nameReply=null){
$this->CI->load->library('MY_phpmailer');
//$this->load->library('MY_phpmailer'); (If you use this function inside CI, use this instead above) I use CI->load above because my function is in a function_helper, not on controller
$mail = new PHPMailer();
$mail->IsSMTP(); //Definimos que usaremos o protocolo SMTP para envio.
$mail->SMTPDebug = 0;
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true; //Habilitamos a autenticaçăo do SMTP. (true ou false)
$mail->SMTPSecure = "tls"; //Estabelecemos qual protocolo de segurança será usado.
$mail->Host = "smtp.office365.com"; //Podemos usar o servidor do gMail para enviar.
$mail->Port = 587; //Estabelecemos a porta utilizada pelo servidor do gMail.
$mail->Username = "your_email#yourdomain.com.br"; //Usuário do gMail
$mail->Password = "Strong_Password"; //Senha do gMail
if($reply != null and $nameReply != null){
//add replyto if you send those values, so you can set other reply address than senders address
$mail->AddReplyTo($reply, $nameReply);
}
$mail->SetFrom('your_email#yourdomain.com.br', 'Senders Name'); //Quem está enviando o e-mail.
$mail->Subject = $subject;
$mail->IsHTML(true);
$mail->Body = $message;
//$mail->AltBody = "Plain text.";
$mail->AddAddress($to);
/*If you want to put attachments that comes from a input FILE type name='file'.*/
if (isset($_FILES['file']) &&
$_FILES['file']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['name']);
}
if(!$mail->Send()) {
// error occur - user your show method to show error
set_msg('msgerro', $mail->ErrorInfo, 'erro');
} else {
// success occur - user your show method to show success
set_msg('msgok', 'E-mail enviado.', 'sucesso');
}
}
Ok, to finish, on controller that you'd want to use this send function:
$this->load->library("MY_phpmailer");
And in your view, when you want to send e-mails:
$this->system->sendmail2($to, $subject, $message); //$to, $subject and $message are vars you sent from your backend - prefer HTML to $message

CodeIgniter: stream socket enable crypto SSL/TLS already set-up for this stream warning

I get a PHP warning (stream_socket_enable_crypto(): SSL/TLS already set-up for this stream) when I send an email using the codeigniter email library from my Ubuntu Server 12.04 LTS VirtualBox VM via my AWS SES. The email is successfully sent in spite of the warning.
// /application/config/email.php:
$config['mailtype'] = 'html';
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://email-smtp.us-west-2.amazonaws.com';
$config['smtp_user'] = 'OMITTED';
$config['smtp_pass'] = 'OMITTED';
$config['smtp_port'] = 465;
$config['newline'] = "\r\n";
$config['wordwrap'] = true;
$config['smtp_crypto'] = 'tls';
My code to send the email is nothing fancy at this point:
$this->load->library('email');
$this->email->from('team#omitted.com', 'Team Omitted');
$this->email->to($person[0]['email']);
$this->email->subject('Temporary password');
$this->email->message('Here is your temporary password:<br />'.$new_pw);
if($this->email->send())
$return['success'] = true;
else
$return['err_msg'] = 'Failed to send password reset email. Please try again';
What exactly is the warning telling me and how can I fix this? Thx in advance!
this resolve the warning when trying to use SSL/TLS smtp crypto with Email librarie in CodeIgniter.
Open the file: /system/libraries/Email.php
Then, into the _smtp_connect() function, you would edit it as follows on the code:
if ($this->smtp_crypto == 'tls')
{
$this->_send_command('hello');
$this->_send_command('starttls');
if( strpos( $this->smtp_host, 'ssl://') === FALSE ) {
stream_socket_enable_crypto($this->_smtp_connect, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT);
}
}
More Info for function stream_socket_enable_crypto: http://php.net/manual/en/function.stream-socket-enable-crypto.php

CodeIgniter + MAMP : unable to send emails

I am trying to send emails with CI running on MAMP free. But it doesn't work, my script is encountering an infinite loop and nothing is happening...
Do i need to set up something especially to send emails from localhost?
Here is my email config for CI:
$config = array();
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = '*****#gmail.com';
$config['smtp_pass'] = '******';
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['newline'] = '\r\n';
Cheers
EDIT: Here is my code to send an email:
$config = array();
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = '****';
$config['smtp_pass'] = '*****';
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['newline'] = '\r\n';
$this->email->initialize($config);
$this->email->from('****');
$this->email->to($email);
$this->email->subject($title);
$this->email->message($content);
$this->email->send();
error_log($this->email->print_debugger());
With $title, $content and $email vars defined in another part of my script. Don't worry about this stuff, I've already checked that my issue is not due to these.
Finally I found the solution:
Send emails with MAMP (mail() PHP function)
Set up SSL: http://soundsplausible.com/2012/01/14/enable-ssl-in-mamp-2-0-5/
Set up Postfix: http://benjaminrojas.net/configuring-postfix-to-send-mail-from-mac-os-x-mountain-lion/
Into MAMP's php.ini (glance phpinfo() to know which version is used and conclude into which folder you need to edit), comment lines SMTP, smtp_port and sendmail_from. Uncomment line sendmail_path and set /usr/sbin/sendmail -t -i as new value.
You should be able to send emails now, if PostFix works fine (run test given in tutorial above).
Send emails with CI
To send emails with CI, you don't need to write your logins into a file for PostFix. However, you need to be able to run PostFix and SSL.
Here is an example of config file for a google account:
$config['protocol'] = "smtp";
$config['smtp_host'] = "smtp.gmail.com";
$config['smtp_port'] = "587";
$config['smtp_user'] = "*****";
$config['smtp_pass'] = "*****";
$config['smtp_crypto'] = "tls"; //very important line, don't remove it
$config['smtp_timeout'] = "5"; //google hint
$config['mailtype'] = "text";
$config['charset'] = "utf-8";
$config['newline'] = "\r\n";
Be careful with " " which are necessary, ' ' could create issues. Here I'm using a TLS connection. If you prefer SSL, use port 465 and fix correctly smtp_crypto value.
You need use sendmail(details how install it on MAMP). Or you can use solution below to store emails in localhost(something like emulate email sending).
I'm use this solution on my localhost(XAMPP). Maybe it will be helpful for you.
Specify path for send mail in php.ini
sendmail_path = "path/to/php path/to/sendmail.php"
The second step - you can try to use this script
define('DIR','path/to/sendmail_dir');
$stream = '';
$fp = fopen('php://stdin','r');
while($t = fread($fp,2048)){
if($t === chr(0)){
break;
}
$stream .= $t;
}
fclose($fp);
$fp = fopen(mkname(),'w');
fwrite($fp,$stream);
fclose($fp);
function mkname($i=0){
$fn = DIR.date('Y-m-d_H-i-s_').$i.'.eml';
if (file_exists($fn)){
return mkname(++$i);
}
else{
return $fn;
}
}

Categories