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

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%'

Related

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);

onPush() function not getting hit after push from controller using ZeroMQ in Guinness of Symfony/Websocket bundle in symfony2

Config.yml
gos_web_socket:
topics:
- #app.real_time.subscribe
- #app.real_time.push
server:
port: 8000 #The port the socket server will listen on
host: localhost #The host ip to bind to
router:
resources:
- #AppBundle/Resources/config/pubsub/routing.yml
client:
firewall: main #can be an array of firewalls
session_handler: #session.handler.pdo
pushers:
zmq:
default: true
host: 127.0.0.1
port: 8888
persistent: true
protocol: tcp
pubsub/routing.yml
real_time_push:
channel: all/user
handler:
callback: 'app.real_time.push' #related to the getName() of your topic
services.yml
app.real_time.subscribe:
class: AppBundle\RealTime\Subscribe
arguments: [ #gos_web_socket.websocket.client_manipulator ]
app.real_time.push:
class: AppBundle\RealTime\Push
arguments: [ #gos_web_socket.websocket.client_manipulator ]
The following function is getting hit when client subscribes on this topic. I can see the text in the console.
Subscribe Class onSubscribe() : Subscribe.php
public function onSubscribe(ConnectionInterface $connection, Topic $topic, WampRequest $request)
{
var_dump("This user is subscribed");
}
But when pushed via zmq from controller the onPush() function never got hit. I have already implemented TopicInterdace and PushableTopicInterface in Push.php.
Push Class onPush() : Push.php
public function onPush(Topic $topic, WampRequest $request, $data, $provider)
{
var_dump("Helloooooooooooooooooo0000000000");
}
Please can any one tell me where did I do wrong. Thanks in advance. Here is the controller
$pusher = $this->container->get('gos_web_socket.zmq.pusher');
//push(data, route_name, route_arguments)
$pusher->push(['my_data' => 'data'], 'real_time_push', ['username' => 'sujit']);

about send mail symfony2, swiftmailer and ovh

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

FOS and Fr3d ldap Bundle with symfony2.1

Login for the first time and getting registered in the database. Though now I got the problem that I can't login a second time.
"symfony/symfony": "2.1.*"
"fr3d/ldap-bundle": "2.0.*#dev"
I have seen similar issies, but if "bindRequiresDn: true" i get in my logs:
[2013-07-10 11:37:18] ldap_driver.DEBUG: ldap_bind(Nikita, **) [] []
[2013-07-10 11:37:18] ldap_driver.DEBUG: 0x1: Failed to retrieve DN for account: Nikita [Binding requires username in DN form] [] []
and can't login.
But if i change:
.../vendor/fr3d/ldap-bundle/FR3D/LdapBundle/Driver/ZendLdapDriver.php
if ($user instanceof LdapUserInterface && $user->getDn()) {
$bind_rdn = $user->getDn();
} else {
$bind_rdn = $user->getUsername();
}
on
if ($user instanceof LdapUserInterface) {
$bind_rdn = $user->getDn();
} else {
$bind_rdn = $user->getUsername();
}
all works good.
My config
fr3d_ldap:
driver:
host: "%ldap_host%"
port: "%ldap_port%"
username: "%ldap_username%"
password: "%ldap_password%"
baseDn: ou=hello, dc=h, dc=i, dc=ru
bindRequiresDn: true
accountFilterFormat: (&(samaccountname=%s))
user:
baseDn: ou=hello, dc=h, dc=i, dc=ru
filter: (&(objectClass=user))
attributes:
- { ldap_attr: samaccountname, user_method: setUsername }
I had problems when initially using FR3DLdapBundle and after logging out and then trying to login the 2nd time.
You may want to read through my blog article here:
Symfony AD Integration
I'm not sure if you already got an answer or got this working, but hopefully this helps someone else out!

Multiple, dynamic database connections in Symfony2

I have a Symfony2 application that I want to make multi-tenant by the use of one database pr tenant (some don't consider this to be multi-tenancy, but that's not really the point).
The documentation describes how to accomplish this. However, I want to be able to create tenants dynamically, and writing the new database connection details (and entity managers) to the config.yml file directly seems messy. I would rather have a separate database which holds the tenants and their connections, and then select the proper connection/em based on an identifier (fetched, for instance, from a the subdomain of the app - clientname.app.com).
Using this approach I should be able to accomplish this, but will at the same time probably break the ability to specify the database connection and/or entity manager when running the command line commands for updating database schemas and the likes.
Provided that what I want to do make sense, is there a clever way to achieve this?
I set ours up with a static database to handle login and tenancy information and a secondary database to hold user data
app/config/config.yml:
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
tenantdb:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
MyCoreBundle: ~
tenantdb:
connection: tenantdb
mappings:
MyAppBundle: ~
And then, in controllers, instead of
$something = $this->getDoctrine()
->getManager()
->getRepository('MyAppBundle:Thing')
->findAll();
we did:
$something = $this->getDoctrine()
->getManager('tenantdb')
->getRepository('MyAppBundle:Thing', 'tenantdb')
->findAll();
which you can find details of here:
http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html
Then, based on Symfony2, Dynamic DB Connection/Early override of Doctrine Service
I set up a service to switch databases based on the subdomain of the request (e.g. tenant1.example.com tenant2.example.com)
src/MyCoreBundle/Resources/config/services.yml:
services:
my.database_switcher:
class: MyCoreBundle\EventListener\DatabaseSwitcherEventListener
arguments: [#request, #doctrine.dbal.tenantdb_connection]
scope: request
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
MyCoreBundle\EventListener\DatabaseSwitcherEventListener.php
namespace MyCoreBundle\EventListener;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\DBAL\Connection;
class DatabaseSwitcherEventListener {
private $request;
private $connection;
public function __construct(Request $request, Connection $connection) {
$this->request = $request;
$this->connection = $connection;
}
public function onKernelRequest() {
$connection = $this->connection;
if (! $connection->isConnected()) {
$params = $this->connection->getParams();
$subdomain = __GET_SUBDOMAIN__();
$oldname = preg_replace (
"/_tenant_$subdomain|_template/",
'',
$params['dbname']
);
$params['dbname'] = $oldname . ($subdomain ? "_tenant_$subdomain"
: "_template");
$connection->__construct(
$params,
$connection->getDriver(),
$connection->getConfiguration(),
$connection->getEventManager()
);
$connection->connect();
}
}
}
For convenience sake, we have an "extra" tenant database called XXX_template which system admins connect to when making global changes.
The plan is that this database is copied to tenant databases on tenant create.
Create a service that produces your custom entity managers based on the user's credential.
$this->get('my.db.service')->getEmForUser('bob');
Then your service would be something like this
class EntityManagerService
{
function __construct($doctrine)
{ ... }
function getEmForUser($user)
{
//look up Bob's connection details in your connection db
//and get them using the globally configured entity manager
//create Entity Manager using bob's config
return $em.
}
This is the most reusable way to do things and it fits with the Dependency Injection pattern Symfony2 uses.
You'll want to return instances of this class
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/EntityManager.php
Don't know if I gresped the extent of your question, but I connect to different databases using this:
$connectionFactory = $this->container->get('doctrine.dbal.connection_factory');
$conn = $connectionFactory->createConnection(array(
'driver' => 'pdo_mysql',
'user' => 'mattias',
'password' => 'nkjhnjknj',
'host' => 'fs1.uuyh.se',
'dbname' => 'csmedia',
));
return $conn;
We had the same problem on our project.
We created a new service in vendor bundle named : connectionManager.
The service is a multiton which return an entityManager by parameters.

Resources