Can't send server emails in CodeIgniter 4 - php

I just hanged up to send server emails.
I'm preparing email sending code like this:
$email_config = Array(
'charset' => 'utf-8',
'mailType' => 'html'
);
$email = \Config\Services::email();
$email->initialize($email_config);
$email->setNewline("\r\n");
$email->setCRLF("\r\n");
$email->setFrom("test#mysite.com", "Sender name");
$email->setTo("receiver#gmail.com");
$email->setSubject("Test message");
$email->setMessage("Hello");
if ($email->send()) {
echo "Email sent!";
} else {
echo $email->printDebugger();
return false;
}
It's showing this error message:
Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.
Date: Thu, 4 Jun 2020 05:21:47 -0500
From: "Sender name" <test#mysite.com>
Return-Path: <test#mysite.com>
Reply-To: <test#mysite.com>
User-Agent: CodeIgniter
X-Sender: test#mysite.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <5ed8cb3ba9e500.94682473#mysite.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_5ed8cb3ba9e702.65790334"
=?UTF-8?Q?Test=20message?=
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_5ed8cb3ba9e702.65790334
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Hello
--B_ALT_5ed8cb3ba9e702.65790334
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Hello
--B_ALT_5ed8cb3ba9e702.65790334--
And giving an error in error log:
Email: sendWithMail throwed Use of undefined constant INTL_IDNA_VARIANT_UTS46 - assumed 'INTL_IDNA_VARIANT_UTS46' (this will throw an Error in a future version of PHP)
I want to mention that,
intl extension is enabled in server.
I'm using cPanel.
It was working fine on Codeigniter 3.
The mail function is working with the row method in my server like this:
$to = 'receiver#gmail.com';
$subject = 'Test message';
$message = 'Hello';
$headers = 'From: test#mysite.com' . "\r\n" .
'Reply-To: test#mysite.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Please help.
Thanks in advance.

You need to setup an MTA on your server (Mail Transfer Agent).
For instance: Postfix or exim, and in some cases nullmailer will do the trick
Possibly you can connect to an SMTP relay of your provider

codeigniter provide alternative types ( Mail, Sendmail and SMTP ) check your cpanel outgoing email configuration or ask your provider to check for php's mail() configuration

I ran into this today, and was surprised to see the library failed out of the box. Seems to be an issue in CI's email lib here:
/**
* Validate email for shell
*
* Applies stricter, shell-safe validation to email addresses.
* Introduced to prevent RCE via sendmail's -f option.
*
* #see https://github.com/codeigniter4/CodeIgniter/issues/4963
* #see https://gist.github.com/Zenexer/40d02da5e07f151adeaeeaa11af9ab36
* #license https://creativecommons.org/publicdomain/zero/1.0/ CC0 1.0, Public Domain
*
* Credits for the base concept go to Paul Buonopane <paul#namepros.com>
*
* #param string $email
*
* #return boolean
*/
protected function validateEmailForShell(&$email)
{
if (function_exists('idn_to_ascii') && $atpos = strpos($email, '#'))
{
$email = static::substr($email, 0, ++$atpos)
. idn_to_ascii(static::substr($email, $atpos), 0, INTL_IDNA_VARIANT_UTS46);
}
return (filter_var($email, FILTER_VALIDATE_EMAIL) === $email && preg_match('#\A[a-z0-9._+-]+#[a-z0-9.-]{1,253}\z#i', $email));
}
I don't have time to investigate what this method is all about (wasted a few hours on this already!), but was able to bypass it and send emails successfully.
Create App/Libraries/Email.php to override the problematic method:
<?php namespace App\Libraries;
class Email extends \CodeIgniter\Email\Email{
protected function validateEmailForShell(&$email){
return TRUE;
}
}
Then make the service return your subclass in App/Config/Services.php:
public static function email(bool $getShared=TRUE){
return $getShared ? static::getSharedInstance('email') : new \App\Libraries\Email();
}

Got a solution from CI forum.
From phpinfo() > intl > ICU version was 4.6 in my case. Which is too old.
Updating that to the latest version worked for me.

Related

how can i use smtp config thats received from form?

i want to use config that i get from html form and i dont want to get it from config/mail.php or .env file
how can i do that in laravel 8
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($address = 'contact#example.com', $name = $this->data['from'])
->subject($this->data['subject'])
->view('mail.view')
->smtp('mail.example.com')
->port('587')
->username('username')
->password('pass')
->smtp('mail.example.com')
->with(['message' => $this->data['message']]);
}
you can use swiftmailer to send any type of mail you want (laravel use this under the hood):
$transport = (new Swift_SmtpTransport("smtp.gmail.com", "587", "tls"))
->setUsername('username')
->setPassword('pass');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message("subject")) // email subject
->setFrom(['contact#example.com' => "sender name"]) // sender mail and display name
->setTo("receiver#gmail.com") // replace with your receiver mail variable
->setBody("<h2>Test</h2>", 'text/html');
$result = $mailer->send($message); // send the mail
if you want to send from queue instead of in controller directly, you can create queue and pass mail parameter to queue construct

How to send email to multiple user email in PHP by set date and hour automatically

I want to send email to multiple user email in PHP automatically by setting a date by the user I mean the user choose a date and hour from input date and I save it on a database then I want to send an email on that date is there any way to PHP do this job automatically because I do this job manually by myself and the number of users is going up and maybe we must send emails in any seconds of a day and I want to do this job in Laravel 5.8 framework when I success on it.
The code I use in a PHP file and run this manually like this:
(I get $UsersEmail array from a database by selecting the date and hour and it's like the array I write in codes).
$UsersEmail = array(
0 => 'user1#example.com',
1 => 'user2#site.com',
2 => 'user3#test.com',
3 => 'user4#somesite.com',
4 => 'user5#anohtersite.com',
);
$AllEmail = '';
foreach($UsersEmail as $user){
$AllEmail .= $user.', ';
}
$to = $AllEmail;
$subject = 'Send Email';
$message = 'This is text message';
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=utf-8';
$headers[] = 'From: My site <info#mysite.com>';
mail($to, $subject, $message, implode("\r\n", $headers));
and I want to do this job in Laravel5.8 framework in the future
My PHP version is 7.2.7 and Laravel version I want to use in the future is 5.8.
You can schedule a command that runs maybe every minute or once every hour, which checks whether any mails are at an appropriate time to be sent. In your table, you would have a flag that tells whether the mail was sent in order not to spam the user or whatever logic you want here. Once you get users, dispatch a job.
SendUserMail Command
public function handle()
{
$users = User::where('mail_sent', false)->whereDate('mail_send_date', '<=', Carbon::now())->get();
ProcessUserMails::dispatch($users);
}
In Kernel you have to register the command
protected function schedule(Schedule $schedule)
{
$schedule->command('send-user-mail')->hourly();
}
ProcessUserMails Job
public function handle()
{
foreach ($this->users as $user) {
$user->notify(new SendMailNotification($user));
$user->update(['mail_sent', true);
}
}
SendMailNotification
public function toMail($notifiable)
{
return (new UserMail($this->user))->to($notifiable->email);
}
UserMail
public function build()
{
return $this->subject('User Custom Email')
->markdown('emails.user.custom_mail');
}
This can be a starting point for you. However, be sure to check Laravel docs about creating commands and notifications as I have only included code snippets.

Not able to send mail in ZF2

call_user_func($this->callable, $to, $subject, $body, $headers, $params);
This was my Function for send mail but it gives following error
{"error-message":"Unable to send mail: Unknown error","error-trace":[{"function":"mailHandler","class":"Zend\Mail\Transport\Sendmail","type":"-\u003E","args":["mujahed69#gmail.com","=?UTF-8?Q?Infinia?=","\u003Cdiv\u003Ehello\u003C/div\u003E","Date: Tue, 03 Nov 2015 09:40:43 +0000\nFrom: =?UTF-8?Q?Infinea=20Team?= \u003Cservice#infiniaretail.de\u003E\nMIME-Version: 1.0\nContent-Type: text/html\nContent-Transfer-Encoding: 8bit\n"," -fservice#infiniaretail.de"]},{"file":"/var/www/html/restaurant/vendor/zendframework/zendframework/library/Zend/Mail/Transport/Sendmail.php","line":139,"function":"call_user_func","args":[[{"__className":"Zend\Mail\Transport\Sendmail"}`
use following link, you use custom function. in that function you should be paste same code of this page
http://framework.zend.com/manual/current/en/modules/zend.mail.introduction.html

CodeIgniter/TankAuth forgot_password function sending emails with no content

Recently moved an existing CodeIgniter product to its own VPS, everything is working away. However, for some reason a password has been invalidated and when the forgot_password function is run the email arrives with an intact subject line, however, the emails have no content. At all. This is the offending code:
function _send_email($type, $email, &$data) {
$this->load->library('email');
$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->to($email);
$this->email->subject(sprintf($this->lang->line('auth_subject_' . $type), $this->config->item('website_name', 'tank_auth')));
$this->email->message($this->load->view('email/' . $type . '-html', $data, TRUE));
echo $this->load->view('email/' . $type . '-html', $data, TRUE);
$this->email->set_alt_message($this->load->view('email/' . $type . '-txt', $data, TRUE));
$this->email->send();
}
I wrote a short PHP script to send an email using the same CodeIgniter library:
<?php
if(!defined('BASEPATH'))
exit('No direct script access allowed');
class EmailTest extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('tank_auth');
$this->lang->load('tank_auth');
}
function sendTest(){
$this->load->library('email');
$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
//$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->to('cameron.j.leafe#gmail.com');
$this->email->subject("Here and There");
$this->email->message("I hear you are an example");
$this->email->send();
echo $this->email->print_debugger();
}
}
?>
That email lands completely fine, and produces this output:
User-Agent: CodeIgniter
Date: Mon, 14 Apr 2014 18:55:55 +1000
From: "EPI Dashboard" <epi#epidashboard.com>
Return-Path: <epi#epidashboard.com>
Reply-To: "epi#epidashboard.com" <epi#epidashboard.com>
X-Sender: epi#epidashboard.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <534ba29b87010#epidashboard.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_534ba29b8708b"
=?utf-8?Q?Here_and_There?=
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_534ba29b8708b
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
I hear you are an example
--B_ALT_534ba29b8708b
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
I hear you are an example
--B_ALT_534ba29b8708b--
The server is a CentOS 6 VPS running postfix and obviously PHP/MySql/Apache.
Any thoughts on what to check or any resources that you can think of would be greatly appreciated.
The PHP.INI file for this server need to have the line:
sendmail_path = /usr/sbin/sendmail -t -i
Which fixed the problem instantly. Not entirely sure as to why parts of the email were showing up and not the body, but it works.

Codeigniter: unable to send email

I have a "Contact Us" page, where if users submit the form. Then email should go to the specified email.
After submiting the form i am getting the Success message ,but i am not seeing any email in my inbox/spam.
I am testing on my live server.
Pelase help me to solve my problem.
My code:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class contact extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->library('email');
$this->load->model('shopmodel');
$this->load->model('contactusmodel');
$this->load->library('form_validation');
}
function index()
{
$this->form_validation->set_error_delimiters(' <li class="errorlist">', '</li>')->set_rules('fullname', 'Name','trim|required|min_length[5]|max_length[50]|xss_clean');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('countryname', 'Country','trim|required|min_length[2]|max_length[50]|xss_clean');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('contactdetails', 'Contact Details','trim|required|min_length[40]|max_length[2000]|xss_clean');
$data=$this->contactusmodel->contactusmodel();
$data["query"] = $this->shopmodel->getshopdetailsById(199);//taking data as shop id 199
if($this->form_validation->run() === FALSE)
{
$data['ffullname']['value'] = $this->input->post('fullname');
$data['fcountryname']['value'] =$this->input->post('email');
$data['femail']['value'] = $this->input->post('countryname');
$data['fcontactdetails']['value'] =$this->input->post('contactdetails');
$this->load->view('contact/contact',$data);
}
else if ($this->form_validation->run() === TRUE)
{
$name=$this->input->post('fullname');
$sendersemail=$this->input->post('email');
$fromcountry=$this->input->post('countryname');
$message=$this->input->post('contactdetails');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'ashutosh10g#gmail.com',
'smtp_pass' => 'xxxxxxxx',
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$email_body ="<div>hello world</div>";
$this->email->from('ashutosh10g#gmail.com', 'ddd');
$list = array('ashutosh10g#gmail.com');
$this->email->to($list);
$this->email->subject('Testing Email');
$this->email->message($email_body);
$this->email->send();
echo $this->email->print_debugger();
}
else{
$this->load->view('contact/contact',$data);
}
}
}
?>
What output i am getting is:
[code]
Your message has been successfully sent using the following protocol: mail
From: "ddd"
Return-Path:
Reply-To: "ashutosh10g#gmail.com"
X-Sender: ashutosh10g#gmail.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <513e1456185d4#gmail.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_513e1456185e3"
=?utf-8?Q?Testing_Email?=
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_513e1456185e3
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
hello world
--B_ALT_513e1456185e3
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<div>hello world</div>
--B_ALT_513e1456185e3--
Maybe you are experimenting a relaying error somtimes the Google Server don't accept relay mail form one MTA to another inbox. Try to test to establish an SMTP dialog to your server an try to send the mail. Here is a simple SMTP dialog example:
http://www.soi.wide.ad.jp/class/20000009/slides/11/6.html
Try to send a mail if the server sends a relay error you should try with another SMTP server. If not maybe is a missconfiguration of your php.
But in my experience gmail always deny the relaying mail for spam and security reasons if the MTA is not a trusted agent.
Another reason may be that you don't have correctly configure DNS Servers and your MTA cannot find the MX Records. Example y your MTA is sendmail it notifies php tha the mail was send succesfully but if you look into sendmail logs you can find that the host is unreachable.

Categories