CakePHP 3 - Emails not sending in production - php

With the code below my emails would send fine in dev mode. Now that I've put my App into production mode when I try to trigger one of the actions to send an email the page just loads and loads until I get the CakePHP error. The data still goes into the database however.
'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,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
'mailjet' => [
'host' => 'in-v3.mailjet.com',
'port' => 587,
'timeout' => 60,
'username' => 'removed',
'password' => 'removed',
'className' => 'Smtp'
],
],
public function register()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$user->role = 'user';
$user->email_verified = '0';
$user->email_token = Security::hash($user->username + microtime(), 'sha1', true);
$user->email_token_expires = strtotime('now');
$user->email_token_expires = strtotime('+1 hour');
if ($result = $this->Users->save($user)) {
$this->Users->lastLogin($user['id']);
$authUser = $this->Users->get($result->id)->toArray();
$this->Auth->setUser($authUser);
$email = new Email();
$email->template('confirm')
->transport('mailjet')
->emailFormat('both')
->viewVars(['token' => $user->email_token])
->to($this->Auth->user('email'))
->from(['removed' => 'Welcome, ' . $user->username . '!'])
->subject('Please confirm your email!')
->send();
$this->Flash->success('You have successfully registered. Check your email to confirm email.');
return $this->redirect(['action' => 'profile']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user', 'userEmail', 'token'));
$this->set('_serialize', ['user']);
}
What could it be?
Error:
Connection timed out
Cake\Network\Exception\SocketException

Last time I got this error, the smtp address was blocked in my production server.
After whitelisting the smtp address everything was fine.

Related

How do I change AD user password by using Adldap2-laravel package?

I would like to change the password of a user in AD since there are no attribute for password in AD.
Currently running laravel framework with Adldap2-laravel package in order to manage ADLDAP operations.
Here's my ldap_auth.php
<?php
return [
'connection' => env('LDAP_CONNECTION', 'default'),
'provider' => Adldap\Laravel\Auth\DatabaseUserProvider::class,
'model' => App\User::class,
'rules' => [
Adldap\Laravel\Validation\Rules\DenyTrashed::class,
],
'scopes' => [
Adldap\Laravel\Scopes\UidScope::class
],
'identifiers' => [
'ldap' => [
'locate_users_by' => 'uid',
'bind_users_by' => 'dn',
],
'database' => [
'guid_column' => 'objectguid',
'username_column' => 'username',
],
'windows' => [
'locate_users_by' => 'samaccountname',
'server_key' => 'AUTH_USER',
],
],
'passwords' => [
'sync' => env('LDAP_PASSWORD_SYNC', false),
'column' => 'password',
],
'login_fallback' => env('LDAP_LOGIN_FALLBACK', false),
'sync_attributes' => [
'username' => 'uid',
'password' => 'userPassword',
'name' => 'cn',
'role' => 'l',
'category' => 'businessCategory',
'telephone_number' => 'telephoneNumber',
'email' => 'mail'
],
'logging' => [
'enabled' => env('LDAP_LOGGING', true),
'events' => [
\Adldap\Laravel\Events\Importing::class => \Adldap\Laravel\Listeners\LogImport::class,
\Adldap\Laravel\Events\Synchronized::class => \Adldap\Laravel\Listeners\LogSynchronized::class,
\Adldap\Laravel\Events\Synchronizing::class => \Adldap\Laravel\Listeners\LogSynchronizing::class,
\Adldap\Laravel\Events\Authenticated::class => \Adldap\Laravel\Listeners\LogAuthenticated::class,
\Adldap\Laravel\Events\Authenticating::class => \Adldap\Laravel\Listeners\LogAuthentication::class,
\Adldap\Laravel\Events\AuthenticationFailed::class => \Adldap\Laravel\Listeners\LogAuthenticationFailure::class,
\Adldap\Laravel\Events\AuthenticationRejected::class => \Adldap\Laravel\Listeners\LogAuthenticationRejection::class,
\Adldap\Laravel\Events\AuthenticationSuccessful::class => \Adldap\Laravel\Listeners\LogAuthenticationSuccess::class,
\Adldap\Laravel\Events\DiscoveredWithCredentials::class => \Adldap\Laravel\Listeners\LogDiscovery::class,
\Adldap\Laravel\Events\AuthenticatedWithWindows::class => \Adldap\Laravel\Listeners\LogWindowsAuth::class,
\Adldap\Laravel\Events\AuthenticatedModelTrashed::class => \Adldap\Laravel\Listeners\LogTrashedModel::class,
],
],
];
Here is my LdapController.php where I include function to reset password
public function resetPassword(Request $req)
{
$req->validate([
'userid' => 'required',
'password' => 'required|min:6|confirmed'
]);
$userLdap = Adldap::search()->where('uid', $req->userid)->firstOrFail();
$newPassword = "{SHA}" . base64_encode(pack("H*", sha1($req->password)));
$res = $userLdap->update([
'userpassword' => $newPassword
]);
//Force change AD Password
// $adPassword = str_replace("\n", "", shell_exec("echo -n '\"" . $req->password . "\"' | recode latin1..utf-16le/base64"));
// $provider = Adldap\Models\User::connect('ad');
// $dn = $provider->search()->where('cn', $req->userid)->get();
// $res = $dn->setPassword($adPassword);
if ($res) {
return back()->withSuccess('<strong>Success!</strong> Your password has been changed');
} else {
return back()->withErrors('<strong>Failed!</strong> Your password was unable to changed');
}
}
Unfortunately $res = $dn->setPassword($adPassword); returns error 'Method Adldap\Query\Collection::setPassword does not exist.'
I found an example here when I searched Google for "Adldap2-laravel change password".
$user = Adldap::users()->find('jdoe');
if ($user instanceof Adldap\Models\User) {
$oldPassword = 'password123';
$newPassword = 'correcthorsebatterystaple';
$user->changePassword($oldPassword, $newPassword);
}
If you want to reset the password, then it seems like this should work:
$user->setPassword("correcthorsebatterystaple");
$user->save();
If you want to know what's going on underneath, or how it can be done without Adldap2-laravel:
The attribute is unicodePwd. You can either "change" the password, or "reset" it.
Changing the password requires knowing the old password. This is what a user would do themselves.
Resetting a password requires the "Reset password" permission on the account, which is usually given to administrative accounts.
The documentation for unicodePwd tells you how to do both. For a "change", you send a delete instruction with the old password and an add instruction with the new one, all in the same request.
For a reset, you send a single replace instruction.
In both cases, the passwords have to be sent in a specific format.
The PHP documentation for 'ldap_modify_batch` shows an example of how to change a password.
On the documentation page for ldap_mod_replace, there is a comment that shows you how to reset a password.

Cakephp 2.x email not working, Why this Error comes

I struck on this problem on many days. Please help. I have followed the cakephp documentation. but could not resolve issue.
Could not send email: unknown
Error: An Internal Error Has Occurred.
Following is Configuration emai.php
<?php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'developer.support#sevenrocks.in',
'charset' => 'utf-8',
'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'SevenRocks'),
'host' => 'ssl://smtp.sevenrocks.in',
'port' => 465,
'timeout' => 30,
'username' => 'developer.support#sevenrocks.in',
'password' => 'developerofsevenrocks',
'client' => null,
'log' => true,
'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
Following is code in controller
$email = new CakeEmail();
$email->emailFormat('html');
$email->from(array($from_email => SITE_NAME));
$email->to($to);
$email->subject($subject);
if ($files)
{
$email->attachments($files);
}
if ( !$email->send($content) )
{
return false;
}
First: to debug CakePHP 2x applications search for debug in your app/Config/core.php and change it to Configure::write('debug', 2); to see the full error message.
Second: Some providers may prevent you from sending Mails via PHP directly (default mail config). A better solution may to use the smtp configuration you provided in email.php.
To use your smtp configuration change your controller code to:
$email = new CakeEmail('smtp');
$email->emailFormat('html');
$email->to($to);
$email->subject($subject);
For more Info see https://book.cakephp.org/2.0/en/core-utility-libraries/email.html#configuration

Why swiftmailer doesn't show senders email in yii2?

I have a problem here. I created a Contact form in my webpage, which includes: name, surname, email and description. When I submit my form, the email sends, but the senders email is my email. F.e:
http://imageshack.com/a/img922/801/eVyutz.png
my.email#gmail.com shows not the email, which user entered in a form, but mine. And after that when I click Reply button and type a message back, I send it to myself. Why?
Here is what I did:
My mailer:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'my.email#gmail.com',
'password' => 'password',
'port' => '465',
'encryption' => 'ssl',
'streamOptions' => [ 'ssl' =>
[ 'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
],
],
My actionContact():
public function actionContact()
{
$model = new Contact();
$model->scenario = Contact::SCENARIO_CREATE;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Success'));
}
else {
Yii::$app->getSession()->setFlash('error', Yii::t('app', 'Failed'));
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
And my model function:
public function sendEmail($email)
{
return Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name." ".$this->surname])
->setSubject($this->subject)
->setTextBody($this->text)
->send();
}
Please help me to solve this, what is wrong? Thank you for any help!
I guess there will be something wrong with $email variable. Because when I use setFrom to email, it shows just my email.
could be you have not assigned a proper value for $this->email (try check for this eg: with var_dump($this->email) and for $this->name and $this->username)
you could use a proper param assigned in param.php
<?php
return [
'adminEmail' => 'my_mail#my_domain.com',
];
.
public function sendEmail($email)
{
return Yii::$app->mailer->compose()
->setTo($email)
->setFrom([\Yii::$app->params['adminEmail'] => $this->name." ".$this->surname])
// ->setFrom([\Yii::$app->params['adminEmail'] => 'try fixed test if $this->name and username not work'])
->setSubject($this->subject)
->setTextBody($this->text)
->send();
}

CakePhp mail not working (smtp)

I am looking a site. I'm new in this site and I don't know CakePhp. This site has users and I try do a forgot password page. I searched but can't a way or missed that.
UsersController.php
...
if ($this->User->save($this->data)) {
App::uses('CakeEmail', 'Network/Email');
$settings = $this->requestAction('pages/setting');
$this->email = new CakeEmail('smtp');
$email = $select['User']['email'];
$content = sprintf('<body> Sevgili ' . $select['User']['username'] . ", <br>
Şifre yenileme talebiniz tarafımıza iletilmiştir.
Aşağıdaki linki tıklayarak yeni şifrenizi belirleyebilirsiniz. <br>
Buraya Tıklayınız <br>
Keyifli Gezintiler <br>
Yukardaki link ile bağlantı sağlayamıyorsanız,
linki web tarayıcınızın adres bölümüne kopyalayabilirsiniz.</body>", $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], $code);
$this->email->from(array($settings['Setting']['smtp_mail'] => $settings['Setting']['title']))
->to($email)
->emailFormat('html')
->subject('Şifre Yenileme [' . time() . ']');
if ($this->email->send($content)) {
$this->Session->setFlash(__('Şifre güncelleme bilgileriniz E-Posta adresinize gönderilmiştir.'), 'default', array('class' => 'success'));
} else {
trigger_error("error Mail");
}
$this->redirect('forgot');
}
And Config/email.php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('mymail#gmail.com' => 'Mysite'),
'host' => 'smtp.gmail.com',
'port' => 587,
'timeout' => 30,
'username' => 'mymail#gmail.com',
'password' => 'mypassword',
'client' => null,
'log' => true,
'charset' => 'utf-8',
'headerCharset' => 'utf-8',
'tls' => true
);
I say again: I'm new worker on this site and another worker used that codes. I don't know why that codes doesn't work now. And I asked that.Thanks a lot for all advices.

Not receiving emails fromCakeMail

I have a weird problem using CakePHP/CakeMail.
I try to send an email for my gmail from the website.
I don't get the email, but I don't get any error either.
The form send the message. The log don't hit anything. Passwords and emails are ok, so what could be wrong?
Here are the codes.
email.php
public $mymail = array(
'transport' => 'Smtp',
'from' => array('xpto#domain.com.br' => 'YourName'),
'sender' => 'my#gmail.com',
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'timeout' => 30,
'username' => 'my#gmail.com',
'password' => 'mygmailpassword',
'client' => null,
'log' => true,
'emailFormat' => 'both'
'charset' => 'utf-8',
'returnPath' => 'xpto#domain.com.br',
'additionalParams' => '-f'.'xpto#domain.com.br',
'headerCharset' => 'utf-8',
);
PagesController.php
public function admin_send_contato() {
if ($this->request->is('post')) {
if(!isset($this->data['email'])){
$this->data['assunto'] = 'Assunto';
}
$email = new CakeEmail('mymail');
$this->Email->return = 'my#gmail.com';
$email->from(array('xpto#domain.com.br' => 'John Doe'))
->to('my#gmail.com')
->subject($this->data['subject'])
->replyTo($this->data['email'])
->send("Name: ".$this->request->data['name']."\nPhone: ".$this->request->data['phone']."\nE-mail: ".$this->request->data['email']."\nMessage: ".$this->request->data['message']);
echo json_encode('ok');
}
$this->autoRender = false;
}
I don't create the site and never used Cake before.
I have no idea what is the problem.
Any thoughts?
Thank you!
I'd recommend using a third party solution to send transactional and marketing emails. Sendgrid is an option and they have documentation to integrate in CakePHP; https://sendgrid.com/docs/Integrate/Frameworks/cakephp.html

Categories