How can I have dynamic Email Config in cakephp - email

I am trying to have a dynamic email config based on the user login. In config/mail.php I have tried like this.
config/mail.php
public $default= array(
"host" => Configure::read("mail_host"),
"port" => Configure::read("mail_port"),
"username" => Configure::read("mail_username"),
"password" => Configure::read("mail_password"),
"transport" => Configure::read("mail_transport")
);
But I am getting error
syntax error, unexpected '(', expecting ')'
I have done like this, But as I am having lots of pages I have to do this for all the pages.
$Email = new CakeEmail("default");
$Email->config(array(
'host' => Configure::read('mail_host'),
'port' => Configure::read('mail_port'),
'username' => Configure::read('mail_username'),
'password' => Configure::read('mail_password'),
'transport' => Configure::read('mail_transport')
));
So that I need to configure dynamically in mail.php. Is it possible please kindly give some solution.

cake 2.0 uses app/Config/email.php
cf. http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
use the constructor to set the config dynamically:
class EmailConfig {
public function __construct() {
$this->default['host'] = Configure::read('mail_host');
...
}

Related

Cakephp 3 Cake\Network\Email configTransport Issue

I'm using Cake\Network\Email\Email class to send some emails.
I have successfully send an email with my smtp configuration that I put on config/app.php
The problem is that I don't want the config to be there.
I have this piece of code:
function enviacorreo($email, $asunto, $content, $cc=null) {
Email::configTransport('gmail', [
'port'=>$smtpport,
'timeout'=>'30',
'host' => $smtp,
'username'=>$smtpuser,
'password'=>$smtppasswd
]);
$email_obj = new Email();
$email_obj->template('default')
->emailFormat('html')
->to($email)
->from([$smtpuser => $nombreSistema])
->subject($asunto)
->transport('gmail');
if($email_obj->send($content))
return array('exito'=>1,'error'=>'Ninguno');
else
return array('exito'=>0,'error'=>'El correo no pudo ser enviado');
}
I'm following the official book here
The error that I get is this:
Transport config "gmail" is missing.
I know that ->transport('gmail'); is looking for a key inside the EmailTransport array definded in app.php
But. How can I have this 'configuration' in my code?
Hope to explained well.
The error message is a little misleading, as the exception is not only being thrown in case the configuration missing, but also in case the className option is missing, which is the case in your example (#7204).
If you look closely at the docs, you should see that you haven't followed it correctly.
[...]
// Sample smtp configuration.
Email::configTransport('gmail', [
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'my#gmail.com',
'password' => 'secret',
'className' => 'Smtp' // <------ there it is
]);
[...]
Cookbook > Email > Configuring Transports

Sending Mail using CakePHP 3.0

I am developing a website with new version 3.0 of CakePHP Framework. I am working on localhost and would like to send an email after a user has filled a form. Below is the code in my controller to send the email.
public function index(){
if ($this->request->is('post'){
$email = new Email();
$email->from([$this->request->data["sender"] => "Sender"]
->to("myEmail#hotmail.com")
->subject($this->request->data["Subject"])
->send($this->request->data["message"]);
}
}
When this code is executed nothing happen, no error, no message in my mailbox. I have seen that it exist in cakephp3.0 a class called DebugTransport but I don't know how to use it in order to debug my code. Someone has already use it ?
Hi thanks everyone for your answer.
By using mailjet.com I was able to send e-mails in localhost. Below the different steps:
Step 1
Create an account on mailjet website
Step 2
In app.php add a new entry in the table EmailTransport. The different parameter host, port, username and password can be found on mailjet website.
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
],
'mailjet' => [
'host' => 'in-v3.mailjet.com',
'port' => 587,
'timeout' => 60,
'username' => 'xxxxx',
'password' => 'xxxxx',
'className' => 'Smtp'
]
],
Step 3
In your controller
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Network\Email\Email;
class ContactController extends AppController {
var $helpers = array('Html');
public function index(){
if($this->request->is('post')){
$userName = $this->request->data['firstname'] . " " . $this->request->data['lastname'];
$email = new Email();
$email->transport('mailjet');
try {
$res = $email->from([$this->request->data['email'] => $userName])
->to(['myEmail#hotmail.com' => 'My Website'])
->subject('Contact')
->send($this->request->data['message']);
} catch (Exception $e) {
echo 'Exception : ', $e->getMessage(), "\n";
}
}
}
You had to use a SMTP server for delivery your email from your localhost in your config email.
There are 2 ways to achieve this:
Use it from a real server with a mail configuration
Use SMTP server for your test on your localhost. there are a lot of SMTP server with let you use it.
see mailjet.com

How to set table schema at table name with Cake?

PostgreSQL, Oracle and many other DBMS's use SCHEMA, so, the table name is
schema_name.table_name
But CakePHP manuals not say anithing about this. What about Model, View and Controller names in the CakePHP defaults? I can use a solution like prefix, that is, where the same schema name will be used at all database operations.
PS1: please not to be confused with method Modelschema, and questions about accessing this method.
PS2: the Bill's 2006 solution is not the better one, because is not updated (I am using CakePHP2) and is not a "official cakePHP solution".
PS3: database.php have some schema attribute? What the link to CakePHP documentation?
Good news for me, there are CakePHP 2.0 documentation about SQL-Schema... No other documentation or examples, but a starting point...
In CakePHP you must define more database config.
In CakePHP 2:
set the 'schema' param to your config
create new configs for all of your schema
use the right schema in your models
For example, database conf:
public $default = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'login' => 'my_db_user',
'password' => 'my_db_passw',
'database' => 'my_project_db',
'prefix' => '',
'encoding' => 'utf8',
'schema' => 'postgres'
);
public $other_schema = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'login' => 'my_db_user',
'password' => 'my_db_passw',
'database' => 'my_project_db',
'prefix' => '',
'encoding' => 'utf8',
'schema' => 'other_schema'
);
If you want to use it in a model:
class AppModel extends AppModel {
public $useDbConfig = 'other_schema';
}
In CakePHP3 is the same way, just there the database is config/app.php and you must use
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');

CakeEmail Could Not Send Email

I need help guys. I can't get this working. Could you help me?
Thanks in advance!
config/email.php
public $default = array(
'transport' => 'Mail',
'from' => 'sender#yahoo.com',
'charset' => 'utf-8',
'headerCharset' => 'utf-8',
);
FeedbacksController.php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
*
*
*
public function send() {
$email = new CakeEmail('default');
$email->emailFormat('text')
->to('recipient#yahoo.com')
->from('sender#yahoo.com')
->send('Message Body');
}
The above code gives me an error:
Could not send email.
Error: An Internal Error Has Occurred.
You can use this :
In the app/config/email.php add this new config
public $gmail = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'adresse#gmail.com',
'password' => 'secret',
'transport' => 'Smtp',
'timeout' => 1
);
After that and in your controller you have to call :
$email = new CakeEmail('gmail');
That is it.
In my experience ive had issues setting the ->from to a single string, and have found that doing ->from(array('emailaddress' => 'name')) has been more successful.
Also im not sure if setting a subject value is required to work sucessfully?

Can't get Auth login to work with CakePHP 2.0

I'm trying to get a simple login form to work using CakePHP 2.0... just Auth, no ACLs for now.
I'm able to see the form and enter the email and password as they are in the database, but I just get returned to the form and the flash error message is displayed. Here is my code:
AppController:
class AppController extends Controller
{
function beforeFilter()
{
$this->Auth->userModel = 'Users';
$this->Auth->fields = array('username' => 'email', 'password' => 'password'); //have to put both, even if we're just changing one
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'hotels', 'action' => 'dashboard');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
}
}
login.ctp:
<?php
echo $this->Form->create('User', array('action' => 'login'));
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
UsersController:
class UsersController extends AppController
{
var $name = 'Users';
var $helpers = array('Html','Form');
var $components = array('Auth','Session');
function beforeFilter()
{
$this->Auth->allow("logout");
parent::beforeFilter();
}
function index() { } //Redirects to login()
function login()
{
if ($this->Auth->login())
{
$this->redirect($this->Auth->redirect());
} else
{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
function logout()
{
$this->redirect($this->Auth->logout());
}
}
?>
I appreciate any help with this. Thanks!
The "Invalid username or password, try again" error is displayed after you hit login?
There are a few things you should check:
• Is the output of $this->Auth->login() identical to the information in your database? Put debug($this->Auth->login()) to see the output in your login method after the form is submitted.
• Are the passwords correctly hashed in the database?
• Try making the AuthComponent available to all your controllers not just the UsersController.
• Not sure if this makes a difference, but call parent::beforeFilter(); before anything else in your controller's beforeFilter method.
EDIT:
Is see that you're trying to validate based on email and password. As a default AuthComponent expects a username and password. You have to explicitly state that you want the email and password to be validated by $this->Auth->login(). This comes from the 2.0 documentation:
public $components = array(
'Auth'=> array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
The fact that you're not seeing any SQL output is to be expected, I believe.
Also you must check if your field "password" in database is set to VARCHAR 50.
It happens to me that I was truncating the hashed password in DB and Auth never happened.
if you are not using defalut "username", "password" to auth, you cant get login
e.g., you use "email"
you should edit component declaration in your controller containing your login function:
$component = array('Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'mot_de_passe')
)
)
));
Becareful with cakephp's conventions. You should change this "$this->Auth->userModel = 'Users';" to "$this->Auth->userModel = 'User';" because User without plural is the Model's convention in cake. That worked for me and also becareful with the capital letters. it almost drived me crazy. Good luck.
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'Events',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'Users',
'action' => 'login',
'home'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username','password' => 'password')
)
)
)
);
Editing the component declaration in AppController did the trick for me. If you have the fields named other than "username" and "password" you should always specify them. In your case it would be
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username' => 'email','password' => 'password')
)
)
)
);
There is a bug in the cakephp tutorial.
$this->Auth->login() should be changed to
$this->Auth->login($this->request->data)