about send mail symfony2, swiftmailer and ovh - symfony

I have a problem of send mail, the mail isn't always send :
sometimes reply with successful sent (and I find it in mailbox)
sometimes reply with failed sent
This's the error message :
Expected response code 250 but got code "", with message « »
This's the content of log file :
[2014-02-27 23:13:43] request.INFO: Matched route "ws_front_message_send" (parameters: "_controller": "Ws\Bundle\MailerBundle\Controller\SendController::messageAction", "domain": "saci.com.tn", "_route": "ws_front_message_send") [] []
[2014-02-27 23:13:43] security.INFO: Populated SecurityContext with an anonymous Token [] []
[2014-02-27 23:13:44] request.CRITICAL: Uncaught PHP Exception Swift_TransportException: "Expected response code 250 but got code "", with message """ at /homez.755/sacinrgm/www/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php line 386 {"exception":"[object] (Swift_TransportException: Expected response code 250 but got code \"\", with message \"\" at /homez.755/sacinrgm/www/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:386)"} []
[2014-02-27 23:13:44] security.DEBUG: Write SecurityContext in the session [] []
my parameters.yml:
parameters:
# smtp ovh parametres
mailer_transport: smtp
mailer_port: 465
mailer_encryption: ssl
mailer_auth_mode: login
mailer_host: ssl0.ovh.net
mailer_user: **************
mailer_password: **************
my action in controller:
public function messageAction(Request $request) {
$message = new Message();
$mailer = $this->get('mailer');
$form = $this->createForm(new MessageCreate(), $message, array(
'action' => $this->generateUrl('ws_front_message_send'),
'method' => 'POST',
'attr' => array('id' => 'form')
));
$form->handleRequest($request);
$mailFrom = $message->getEmail();
$mailTo = $this->container->getParameter('mailer_customer');
$mail = \Swift_Message::newInstance()
->setSubject('Contact ' . $message->getCountry() . ' from Saci')
->setFrom($mailFrom)
->setTo($mailTo)
->setBody($this->renderView('WsMailerBundle:Email:message.html.twig', array('message' => $message)), 'text/html');
$mailer->send($mail);
$this->get('session')->getFlashBag()->set(
'succes', 'contact.msg_after_send');
return $this->redirect($this->getRequest()->headers->get('referer'));
}

I you have trouble with email and spam with ovh, siwftmailer and fosUserBundle,
please consider adding this in your config.yml
fos_user:
from_email:
address: noreply#yourdomain.com
sender_name:
yourname
If you don't do this, fos user bundle will send the email with noreply#exemple.com and OVH flag this as spam.
source: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/emails.md

Related

What can I do to resolve this pusher error-JSON returned from auth endpoint was invalid, yet status code was 200?

I still have this problem after asking the same question here: JSON returned from auth endpoint was invalid, yet status code was 200 with no response. I've looked at similar questions and followed the
suggestions: setting my broadcast driver to 'pusher', uncommenting 'App/BroadcastServiceProvider' class in my app.config file, setting debug mode to false in my .env file, etc. I have also looked at pusher docs but the issue remains unresolved for me.
I have updated my previous attempt by adding '/broadcasting/auth/' auth endpoint and headers but still the same error. But I can now see a 302 redirect to the auth route then a 302 redirect to the login route then to the dashboard with a 200 response on laravel telescope, which I wasn't seeing before now. So this suggests to me that adding the auth endpoint ought to resolve the issue but it doesn't.
I also tried setting up and using a '/pusher/auth/' auth end point route and controller but it gave me a 'Failed to load resource: the server responded with a status of 405 (Method Not Allowed)' along with "Error: Unable to retrieve auth string from auth endpoint - received status: 405 from /pusher/auth, but not the previous invalid json error. I get this with a 'get' request to the controller but a 500-internal server error with a 'post' request. I really don't know which is correct.
This is my bootstrap.js file:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true,
authEndpoint: '/broadcasting/auth',
//authEndpoint: '/pusher/auth',
auth: {
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
}
}
});
This is one pusherController I created:
public function pusherAuth(Request $request)
{
$key = getenv('PUSHER_APP_KEY');
$secret = getenv('PUSHER_APP_SECRET');
$app_id = getenv('PUSHER_APP_ID');
$pusher = new Pusher($key, $secret, $app_id);
$auth = $pusher->socket_auth($_GET('channel_name'), $_GET('socket_id'));
return response($auth, 200);
}
I now know my vue frontend file that should receive and display the broadcast checks out and the issue has to do with resolving this pusher subscription error.
Any help will be appreciated.
Check your .env for the correct Broadcast driver:
BROADCAST_DRIVER=pusher
I was finally able to resolve this issue. The problem was entirely an authentication issue as the error messages pointed out. While I still don't know why the built in '/broadcast/auth' endpoint didn't work, my initial attempt to authenticate by creating a '/pusher/auth/' was wrong in the way I set up the route and controller.
The correct route set up should be 'post' and call a controller, using a closure based route didn't work for me. My previous (see above) implementation of the controller was also wrong.
This is the controller code that worked:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Pusher\Pusher;
class PusherController extends Controller
{
/**
* Authenticates logged-in user in the Pusher JS app
* For private channels
*/
public function pusherAuth(Request $request)
{
$user = auth()->user();
$socket_id = $request['socket_id'];
$channel_name =$request['channel_name'];
$key = getenv('PUSHER_APP_KEY');
$secret = getenv('PUSHER_APP_SECRET');
$app_id = getenv('PUSHER_APP_ID');
if ($user) {
$pusher = new Pusher($key, $secret, $app_id);
$auth = $pusher->socket_Auth($channel_name, $socket_id);
return response($auth, 200);
} else {
header('', true, 403);
echo "Forbidden";
return;
}
}
}
This is the final bootstrap.js file:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true,
authEndpoint: '/pusher/auth',
auth: {
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
}
}
});
And my route code in web.php:
Route::post('/pusher/auth', [PusherController::class, 'pusherAuth'])
->middleware('auth');
Pusher console log:
Pusher : : ["Event recd",{"event":"pusher_internal:subscription_succeeded","channel":"private-user.3","data":{}}]
vendor.js:41325 Pusher : : ["No callbacks on private-user.3 for pusher:subscription_succeeded"]

send private replies keep asking for pages_messaging while my token already have that permission

I am trying to send private replies to comments on a page, I get user token with
$
fb = new Facebook\Facebook([
'app_id' => FB_APP_ID,
'app_secret' => FB_APP_SECRET,
'default_graph_version' => 'v3.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['leads_retrieval','email','publish_pages','manage_pages','pages_show_list','pages_messaging','pages_manage_cta','read_page_mailboxes','pages_messaging_subscriptions'];
$loginUrl = $helper->getLoginUrl('//abc.com/fb-callback.php', $permissions);
the I create token for page as following
$requestxx = new Facebook\FacebookRequest(
$fbApp,
$token,//my user access token
'GET',
'/pageID?fields=access_token',
array('ADMINISTER')
;
$responset = $fb->getClient()->sendRequest( $requestxx );
$json = json_decode( $responset->getBody() );
$page_access_token = $json->access_token;
then I debugged my page token and it has "pages_messaging", permission but when I try to send private reply to a comment I get
Graph returned an error: (#230) Requires pages_messaging permission to manage the object
My code to send private replies
$fb->post('/comment_id/private_replies',$message,$page_access_token);
I am stuck here for three days, please help me

AccessDeniedException in log before rewriting

In 4.1 when a user want to access in page with security (#Security("has_role('ROLE_ADMIN')" for example), the user will be redirect in the login page. It's working. I have no error 500.
But in my log /var/log/prod.log i have some error :
[2018-06-06 09:30:47] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Security\Core\Exception\AccessDeniedException: "Access Denied." at /var/www/website/vendor/symfony/security/Http/Firewall/AccessListener.php line 68 {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): Access Denied. at /var/www/website/vendor/symfony/security/Http/Firewall/AccessListener.php:68)"} []
[2018-06-06 09:30:47] security.DEBUG: Access denied, the user is not fully authenticated; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): Access Denied. at /var/www/website/vendor/symfony/security/Http/Firewall/AccessListener.php:68)"} []
[2018-06-06 09:30:47] security.DEBUG: Calling Authentication entry point. [] []
I don't understand why I have critical error.
Symfony Framework defines a Symfony\Component\HttpKernel\EventListener\ExceptionListener that subscribes to KernelEvents::EXCEPTION with very high priority of 2048 for method logKernelException (see https://github.com/symfony/http-kernel/blob/master/EventListener/ExceptionListener.php#L93) :
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => array(
array('logKernelException', 2048),
array('onKernelException', -128),
),
);
}
So thrown AccessDeniedException is firstly handled by this logKernelException method that logs it with CRITICAL level (see https://github.com/symfony/http-kernel/blob/master/EventListener/ExceptionListener.php#L109) :
protected function logException(\Exception $exception, $message)
{
if (null !== $this->logger) {
if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
$this->logger->critical($message, array('exception' => $exception));
} else {
$this->logger->error($message, array('exception' => $exception));
}
}
}
At this step, AccessDeniedException has been logged on the request channel. It's totally relevant from the request scope : original request has failed because no authentication had been performed...
Then, Symfony\Component\Security\Http\Firewall\ExceptionListener, listening KernelEvents::EXCEPTION but handling only authentication related ones (see https://github.com/symfony/security/blob/master/Http/Firewall/ExceptionListener.php#L87) goes on duties in order to redirect to authentication start point...

Can't send emails using SwiftMailer (Symfony4): wrong SMTP parameters?

I'm coding a small website using Symfony 4.
There's a simple contact form that is supposed to send emails, seemed easy until I realize I can't configure it ^^
I've followed Symfony doc instructions from here:
[https://symfony.com/doc/current/email.html][1]
Meaning mainly having the Swift mailer dependy:
composer require mailer
And my Controller looks like this:
/**
* #Route("/contact", name="contact_handling")
*/
public function contactHandler(Request $request, \Swift_Mailer $mailer)
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$message = (new \Swift_Message('Hello Email'))
->setFrom('send#example.com')
->setTo('myownemail#hotmail.fr')
->setBody("plopppp mail")
;
$mailer->send($message);
$contact = $form->getData();
return $this->render('home.html.twig', array(
'form' => $form->createView(),
));
}
return $this->render('home.html.twig', array(
'form' => $form->createView(),
));
No matter what it does next in the return (I'm also trying to figure out how to avoid the page reload and just return an answer like "OK" or "not OK" then my Javascript pops up a message)
For dev environment (I'll have the same problem when moving to prod by the way),
my .env conf file has this parameter:
MAILER_URL=smtp://smtp-mail.outlook.com:587?encryption=tls&username=myownemail#hotmail.fr&password=mypwd
while trying to use my own email account, which could be my problem
Smtp address, port and encryption are some parameters found on website like this one:
[https://www.lifewire.com/what-are-the-outlook-com-smtp-server-settings-1170671][1]
Of course, I've never received anything.
If someone familiar whith this could help me it would be very nice :)
I'm using Windows10 + PhpStorm + php7 + built-in symfony server
Thanks!
Edit:
Output from: php bin/console debug:config SwiftmailerBundle
swiftmailer:
default_mailer: default
mailers:
default:
url: '%env(MAILER_URL)%'
spool:
type: memory
path: 'C:\www\h4h\var\cache\dev/swiftmailer/spool'
id: null
transport: smtp
command: '/usr/sbin/sendmail -bs'
username: null
password: null
host: localhost
port: null
timeout: 30
source_ip: null
local_domain: null
encryption: null
auth_mode: null
delivery_addresses: { }
logging: true
delivery_whitelist: { }
Edit 2:
I've just tried putting the conf in the config/packages/swiftmailer.yaml without more success, but at least, php bin/console debug:config SwiftmailerBundle outputs the correct info:
swiftmailer:
transport: gmail
username: mylogin
password: mypwd
host: smtp.gmail.com
port: 587
encryption: ssl
auth_mode: login
spool:
type: file
path: '%kernel.cache_dir%/swiftmailer/spool'
sender_address: ~
antiflood:
threshold: 99
sleep: 0
delivery_addresses: []
disable_delivery: ~
logging: '%kernel.debug%'

symfony validation doesn't work

I guess there is something I'm missing.
I have a User entity which is validated through a yml file but every time I send a post request to the route it seems it doesn't get my request. With this I mean that the route works fine but I keep getting the error messages that the password and username should not be blank (due to the constraints i set). So it seems it's not getting my request validated against the entity.
I made sure to have this settings triggered in my config:
validation: { enabled: true, enable_annotations: true }
Here is my routing.yml:
user_login_homepage:
path: /check
defaults: { _controller: UserLoginBundle:Login:checkCredentials }
methods: [POST]
Here is my validation.yml
User\UserBundle\Entity\User:
properties:
username:
- NotBlank: ~
password:
- NotBlank: ~
Here is my controller (LoginController.php)
public function checkCredentialsAction(Request $request)
{
$recursiveValidator = $this->get('validator');
$user = new User();
$errors = $recursiveValidator->validate($user);
if (count($errors) > 0) {
$errorsString = (string) $errors;
return new Response($errorsString);
}
return new Response('Yuppy');
}
I've just tried to follow the instructions but I'm not able to have it work :(
Am I missing something?
you are creating an empty User so It's correct the error, try this (I have imagine that username and password are passed into POST data right?):
$user = new User();
$postData = $request->request->all();
$user->setUsername($postData['username'];
$user->setPassword($postData['password'];
$errors = $recursiveValidator->validate($user);

Resources