Swiftmailer send status - symfony

How to check send status in swiftmailer with symfony?
I send mails this way:
$res = $this->get('mailer')->send($message)
Now $res has always status 1 even if I set wrong password in parameters. Email isn't send and status is 1 :/
I'd like to throw some kind of information if there is any problem with sending :/

You can use second argument in send()
$res = $this->get('mailer')->send($message, $errors)

try {
$this->get('mailer')->send($message);
}
catch (\Exception $exception) {
$errors = $exception->getMessage();
}
The $errors variable will contain the message if sending fails.

Related

Asserting email was sent with mailhog dsn

Testing my email sending logic, doesn't catch the sent email to mailhog.
// Both ways don't work
$this->assertEmailCount(1, 'smtp://mailhog:1025');
$this->assertEmailCount(1);
Errors I got for both:
Failed asserting that the Transport smtp://mailhog:1025 has sent "1" emails (0 sent).
Failed asserting that the Transport has sent "1" emails (0 sent).
Email is sent. I see it in mailhog. Everytime I run the tests.
private function getMailer(array $mailConfig): MailerInterface
{
$dsn = match (strtolower($mailConfig['transport'])) {
'sendgrid' => 'smtp://mailhog:1025',
'mailchimp' => 'smtp://mailhog:1025',
default => 'smtp://mailhog:1025'
};
$transport = Transport::fromDsn($dsn);
return new Mailer($transport);
}
Posting the sending functionality as well but think it doesn't matter when email is sent. Is there something specific when testing with mailhog?
I got the same problem, and I just add
//...
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Mailer\Mailer;
public function __construct(
//...
private readonly EventDispatcherInterface $eventDispatcher
) {
}
public function getMailer(): Mailer
{
//...
$transport = Transport::fromDsn($dsn, $this->eventDispatcher);
return new Mailer($transport);
}
You can also disable delivery in your tests https://symfony.com/doc/current/mailer.html#disabling-delivery

Using Swift Mailer with smtp on Symfony 4

I installed Swift Mailer on Symfony 4 to send a registration email for new users. What I noticed is that it works fine when I use my Gmail account to send emails, but it doesn't work when I use my Outlook.
So after reading the documentation, I set the MAILER_URL on my .env file like this
> MAILER_URL=smtp://localhost:25?encryption=ssl&auth_mode=login&username=*****%40live.com&password=******
I also used :
> MAILER_URL=smtp://smtp-mail.outlook.com:25/encryption=ssl&auth_mode=login&username=*******%40live.com&password=********
I have changed the port from 25 to 587 to 465 and none of those worked either.
This is the method where I call the mailer :
public function sendMail($subject, $fromEmail, $toEmail, $emailTemplate, $argumentsArray, $emailType, $imgPath)
{
$message = $this->setBasicEmailMessage($subject, $fromEmail, $emailTemplate, $argumentsArray, $emailType, $imgPath);
$message->setTo($toEmail);
$this->mailer->send($message);
}
private function setBasicEmailMessage($subject, $fromEmail, $emailTemplate, $argumentsArray, $emailType, $imgPath)
{
$message = (new \Swift_Message($subject))->setFrom($fromEmail);
$img = $message->embed(\Swift_Image::fromPath($imgPath));
$argumentsArray['img'] = $img;
$message->setBody(
$this->templating->render(
$emailTemplate,
$argumentsArray
),
$emailType
);
return $message;
}
And this is my swiftmailer.yaml:
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
The code doesn't raise an exception but the email never makes it to the users.
Does anyone have an idea how to fix this?
Put send function in try and catch block you will get definitely any clue:
try {
$this->mailer->send($message);
} catch (\Swift_RfcComplianceException $e) {
echo "\nException :: " . $e->getMessage();
}

Silex - my error handler isn't working

I am trying to set up a error handler on my controller to catch anything that might cause my page to malfunction. For example: in this scenario I am trying to catch any error that could possibly happen once my method calls a external API with a bad parameter but it doesn't seem to do anything except give me the typical ClientException in Middleware.php line 69:
Client error: 400 which isn't what I am exactly aiming for. Any advice will be greatly be appreciated or better ways of handling errors in Silex.
private function getSIS($url, $session, Application $app)
{
$message = "You don't have permission to access this!";
if($app['security']->isGranted('ROLE_SUPER_ADMIN'))
{
$client = new Client(['base_uri' => 'https://***********.ca/api/SIS/']);
if (!empty($session))
$response = $client->get($url, ['query' => 'session=' . $session]);
else
$response = $client->get($url);
return $response;
}
$app->error(function (\Exception $e, $code) {
switch($code) {
case 404:
$message = 'The requested page could not be found';
break;
default:
$message = 'We are sorry, but something went terribly wrong.';
}
return new Response($message);
});
return new Response($message);
}
The $app->error method might need to be placed outside the context of your controller actions. I'm not sure exactly how you have your application structured but maybe try placing the error block right before $app->run();
$app->error(function (\Exception $e, $code) use ($app) {
switch($code) {
case 404:
$message = 'The requested page could not be found';
break;
default:
$message = 'We are sorry, but something went terribly wrong.';
}
return new Response($message, $code);
});
$app->run();

Symfony2: transactions fail with "There is no active transaction."

I've spend several hours trying to resolve this issue. Google and Stackoverflow didn't help much either. So any advice is most welcome here.
I'm trying to apply a rollback logic with transactions when updating two tables in relation:
The code in general is:
// ...
$em = $this->getDoctrine()->getEntityManager();
$em->getConnection()->beginTransaction();
foreach($dataArr as $data) {
$userObj = $em->getRepository('AcmeBundle:User')->find($userId);
$userObj->setActive(1);
$em->persist($userObj);
$em->getConnection()->commit();
}
$storeObj = $em->getRepository('AcmeBundle:Store')->find($storeId);
$storeObj->setIsOpen(1);
$em->persist($storeObj);
$em->getConnection()->commit();
try {
$em->flush();
$em->clear();
} catch(Exception $e) {
$em->getConnection()->rollback();
$em->close();
throw $e;
}
My PDO drivers are enabled, updating without transactions works as expected, but once I beginTransaction() and try to commit() nothing works and I get the There is no active transaction. exception.
Some sources suggested using only commit() without persist() but it doesn't make any difference. I'm probably doing something really stupid here, but I just cannot see what it is.
After
$this->em->getConnection()->beginTransaction();
you must write:
$this->em->getConnection()->setAutoCommit(false);
It works for me :)
I once accidentally got this error
by doing following:
$em->getConnection()->beginTransaction();
try {
$em->persist($entityA);
$em->flush();
$em->persist($entityB);
$em->flush();
$em->getConnection()->commit();
//exception thrown here
$mailer->send($from, $to, $subject, $text);
} catch (\Exception($ex)) {
$em->getConnection()->rollback();
}
So, you already have guessed that there should not be any code after commit as in the case when this arbitary code($mailer service in our example) throws an exception transaction would be closed before the moment catch block is executed. Maybe this will save a minute or two to somebody:)
Since the version 1.5.2 of DoctrineBundle, you can configure the connection to use auto_commit in the configuration of your project.
# app/config/config.yml (sf2-3) or config/doctrine.yaml (sf4)
doctrine:
dbal:
auto_commit: false
As #prodigitalson correctly suggested I needed to do a commit() before the flush() in order for the get the queries executed. So the working code now is:
$em = $this->getDoctrine()->getEntityManager();
$em->getConnection()->beginTransaction();
foreach($dataArr as $data) {
$userObj = $em->getRepository('AcmeBundle:User')->find($userId);
$userObj->setActive(1);
$em->persist($userObj);
// this is no longer needed
// $em->getConnection()->commit();
}
$storeObj = $em->getRepository('AcmeBundle:Store')->find($storeId);
$storeObj->setIsOpen(1);
$em->persist($storeObj);
// this is no longer needed
// $em->getConnection()->commit();
try {
// Do a commit before the FLUSH
$em->getConnection()->commit();
$em->flush();
$em->clear();
} catch(Exception $e) {
$em->getConnection()->rollback();
$em->close();
throw $e;
}

Sending a HTTP Post from magento 1.6 after customer registration?

can anyone point me in the right direction I need to send a HTTP post when a customer registers and or makes a purchase from Magento to a third part server ?
It will be the basic information like name, address, postcode , email ect.
Not sure where to start ?
Many thanks
$client = new Varien_Http_Client('http://www.example.com/');
$client->setMethod(Varien_Http_Client::POST);
$client->setParameterPost('name', $name);
$client->setParameterPost('address', $address);
//more parameters
try{
$response = $client->request();
if ($response->isSuccessful()) {
echo $response->getBody();
}
} catch (Exception $e) {
}

Resources