using mailer in Symfony 4.3- > Expected response code "250" but got code "535", with message "535-5.7.8 Username and Password not accepted - symfony

I'm stuck. I'm using mailer from symfony with gmail generated password, and i keep on getting this error.
Would anyone have an idea as of why?
here's my controller:
public function new(Request $request): Response
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($contact);
$entityManager->flush();
$name = ($form['Name']->getData());
$email = ($form['Email']->getData());
$subject = ($form ['Subject']->getData());
$content = ($form['Content']->getData());
$transport = new GmailTransport('******#*********.org', '******************');
$mailer = new Mailer($transport);
$entityManager = $this->getDoctrine()->getRepository(Subject::class);
$toEmail = $subject -> getEmail();
$realSubject = $subject -> getName();
$message = (new TemplatedEmail())
->from($email)
->to($toEmail)
->subject($content)
// path of the Twig template to render
->htmlTemplate('mail/newContact.html.twig')
/* pass variables (name => value) to the template
->context([
'expiration_date' => new \DateTime('+7 days'),
'username' => 'foo',*/
;
$mailer->send($message);
return $this->redirectToRoute('home');
}
return $this->render('contact/new.html.twig', [
'contact' => $contact,
'form' => $form->createView(),
]);
}
and i've got this in the .env
###> symfony/mailer ###
MAILER_DSN=smtp://******#*********.org:******************#gmail
###< symfony/mailer ###
does anyone have an idea?
Thank you

Related

How to use a request post data in findOneBy method

I am writing a method to request a password reset in symfony
I get the email of the user from the posted value
$data = $form->getData();
$email = $data['email'];
It seems that I get the good email value and I can verify it by a
dump($email);
that returns
"firstname.name#domain.ext"
Then I try to fetch a user in the database with
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => $email]);
but the result is null.
After that I try 2 different ways and both of them work perfectly i.e. give a valid user.
1- I replace
$email = $data['email'];
with
$email = "firstname.name#domain.ext";
2-
I change the line that fetches the user with:
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => "firstname.name#domain.ext"]);
Obviously the trouble comes from the way the value is passed to the findOneBy method, not because the user is not in the database.
I would like to know what I should do to use the value I got from the Post ?
Here is my controller
/**
* #Route("/passforgotten", name="app_forgotten_password", methods="GET|POST")
*/
public function askResetPass(
Request $request,
UserPasswordEncoderInterface $encoder,
ManagerRegistry $managerRegistry,
\Swift_Mailer $mailer,
TokenGeneratorInterface $tokenGenerator
): Response {
$defaultData = ['message' => 'Type your message here'];
$form = $this->createFormBuilder($defaultData)
->add('email', EmailType::class)
->add('send', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$email = $data['email'];
//alternative that works of course with a real email
//$email="firstname.name#domain.ext";
dump($email);
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => $email]);
dump($email);
dump($user);
if ($user === null) {
$this->addFlash('danger', 'Email Inconnu, recommence !');
return $this->redirectToRoute('app_register');
}
$token = $tokenGenerator->generateToken();
$manager = $managerRegistry->getManager();
try {
$user->setResetPasswordToken($token);
$manager->flush();
} catch (\Exception $e) {
$this->addFlash('warning', $e->getMessage());
return $this->redirectToRoute('home');
}
//this has not been tested yet
$url = $this->generateUrl('security/ask_reset_password', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
$message = (new \Swift_Message('Rénitialisation du mot de pass'))
->setFrom(array('symfony#domain.ext'))
->setTo($user->getEmail())
->setBody('hello ask for reset pass!'
);
$mailer->send($message);
$this->addFlash('notice', 'Mail correctement envoyé !');
//this is not finished
return $this->redirectToRoute('a_route');
}
return $this->render('security/ask_reset_password.html.twig', [
'form' => $form->createView()
]);
}
Sorry but I was passing a misspelled email a letter l just before a b was missing and I used the form memorization of it each time. In fact it works in every case.

auto-responder with login details in Symfony

Here is the funcion im using
public function sendCredentialsEmailMessage(UserInterface $user)
{
$template = 'Emails/afterRegister.html.twig';
$rendered = $this->templating->render($template, array(
'user' => $user,
));
$this->sendEmailMessage($rendered,
$this->parameters['from_email']['confirmation'], $user->getEmail());
}
Basically I want the auto-mailer to send my template along with the login name. When i create a new user nothing is being sent. My email template is located in app>resources>views>emails>
and this controller file is located in src>myname>userbundle>mailer>
protected function sendEmailMessage($renderedTemplate, $fromEmail, $toEmail)
{
// Render the email, use the first line as the subject, and the rest as the body
$renderedLines = explode("\n", trim($renderedTemplate));
$subject = array_shift($renderedLines);
$body = implode("\n", $renderedLines);
$message = (new \Swift_Message())
->setSubject($subject)
->setFrom($fromEmail)
->setTo($toEmail)
->setBody($body);
$this->mailer->send($message);
}
Also this works for sure:
public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['resetting.template'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()),
UrlGeneratorInterface::ABSOLUTE_URL);
$rendered = $this->templating->render($template, array(
'user' => $user,
'confirmationUrl' => $url,
));
$this->sendEmailMessageCustom($rendered, $this->from, (string)$user->getEmail(),'Password resseting');
}

ContextErrorException Notice: Undefined variable - but it did work before

public function contactAction(Request $request)
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$em = $this->getDoctrine()->getManager();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$name = $form['name']->getData();
$email = $form['email']->getData();
$subject = $form['subject']->getData();
$message = $form['message']->getData();
$contact->setName($name);
$contact->setEmail($email);
$contact->setSubject($subject);
$contact->setMessage($message);
}
$message = \Swift_Message::newInstance()
->setSubject($subject) // here the error
->setFrom('jardisindustrie#gmail.com')
->setTo($email)
->setBody($this->renderView('sendmail.html.twig', array(
'name' => $name,
'message' => $message,
'email' => $email,
'subject' => $subject)), 'text/html');
$this->get('mailer')->send($message);
return $this->render('SDCoreBundle::contact.html.twig', [
'form' => $form->createView()
]);
}
I don't know why but it did work good and this afternoon I try again and I have the error message...
I want to make a contact form with swiftmailer, normally I do like that but here i don't know why there is a trouble.
Thanks for your help
You are missing the complete error message. But from the first look, the code that creates and sends a message should be inside the if($form->isSubmitted() && $form->isValid()) block, otherwise it will try to send a message when the form is not submited but only being displayed.

Functional Testing in Symfony

I am new in testing.I want to test my function.I have successfully installed phpUnit. I check many tutorials on internet.But I could not get the proper information regarding testing. Here is the my function code:
public function loginAction(Request $request)
{
$session = $this->getRequest()->getSession();
if( $session->get('userId') && $session->get('userId') != '' && $session->get('type') == '2')
{
//if user is login then it will be redirect to login page
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('DRPAdminBundle:User');
if ($request->getMethod() == 'POST')
{
$session->clear();
$userName = $request->get('username');
$password = md5($request->get('password'));
//find email, password type and status of User
$user = $repository->findOneBy(array('username' => $userName, 'password' => $password,'type'=>2,'status'=>1 ));
$userEmail = $repository->findOneBy(array('email' => $userName, 'password' => $password,'type'=>2,'status'=>1 ));
if ($user)
{
//set session of User login
$session->set('userId', $user->getId());
$session->set('type', 2);
$session->set('nameRegistrar', $user->getFirstName());
$session->set('pictureRegistrar', $user->getPicture());
//echo "<pre>";print_r($session->get('picture'));die;
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
if ($userEmail)
{
$session->set('type', 2);
$session->set('userId', $userEmail->getId());
$session->set('nameRegistrar', $userEmail->getFirstName());
$session->set('pictureRegistrar', $userEmail->getPicture());
//echo "<pre>";print_r($session->get('picture'));die;
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
else
{
return $this->render('DRPRegistrarGeneralBundle:Pages:login.html.twig', array('name' => 'Invalid Email/Password'));
}
}
return $this->render('DRPRegistrarGeneralBundle:Pages:login.html.twig');
}
how to test this function? Please help
I don't know what you want to test but here is an exemple of what you can do to test user fonctionnalities :
public function testUserPageDown()
{
$client = static::createClient();
$client->request('GET', '/user/login');
$this->assertTrue($client->getResponse()->isSuccessful());
$client->request('GET', '/user/register');
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function testUserFirewall()
{
$client = static::createClient();
//Trying go to user routes without being logged
$client->request('GET', '/user/profile');
$this->assertTrue($client->getResponse()->isRedirect());
$client->request('GET', '/user/profile/edit');
$this->assertTrue($client->getResponse()->isRedirect());
$client->request('GET', '/user/profile/editpassword');
$this->assertTrue($client->getResponse()->isRedirect());
}
public function testUserFormRegister()
{
$client = static::createClient();
$crawler = $client->request('GET', '/user/register');
$buttonCrawlerNode = $crawler->selectButton('submit_user_register');
$form = $buttonCrawlerNode->form();
$testForm = array(
'wineot_databundle_user[username]' => 'test',
'wineot_databundle_user[firstname]' => 'test',
'wineot_databundle_user[lastname]' => 'test',
'wineot_databundle_user[mail]' => 'test#mail.fr',
'wineot_databundle_user[plain_password][first]' => 'blabla321',
'wineot_databundle_user[plain_password][second]' => 'blabla321'
);
$response = $client->getResponse();
$client->submit($form, $testForm);
//If the submit is true that mean that the register is ok
$this->assertTrue($response->isSuccessful());
}
I hope that will help you do undestand how to test.

get('security.context')->isGranted in functional test

I want do one functional test over on service Symfony2. The idea is call before to the controller and after that, load the service with the function. The function is this one:
function save($title,$description,$setId,$html,$validate,$articles){
$articles = explode(',', $articles);
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
}else{
$profileId = $this->container->get('security.context')->getToken()->getUser()->getId();
$userName = $this->container->get('security.context')->getToken()->getUser()->getUserName();
}
}
and now my test code is :
$client = static::createClient();
$crawler = $client->request('GET','/sets/save',
array(
"title"=>"rtyui",
"description"=>"aksdjhashdkjahskjdh",
"set_id"=>"",
"html"=>"",
"validate"=>1,
"articels"=>"3,4"
)
);
but doesn't work already that I have this lines:
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
Now, the question is, how i can do the validation process? I've tried to do this validation process as show the documentation:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'pa$$word',
));
but I got the same error.
Also you can login user by Security Token:
$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
new UsernamePasswordToken(
$user, null, 'main', $user->getRoles()
)
);
Where:
$user - instance of User entity with role ROLE_USER,
main - your security provider name

Resources