I can't get SwiftMailer to send in a Symfony2 Command - symfony

I'm trying to setup a Command to send out warning emails, but I can't get SwiftMailer to actually send them.
I read some posts about flushing the Spooler but I am still not seeing emails going to Postfix.
The emails do work in a controller, and I receive them. So I know that Postfix itself is working, and that SwiftMailer works from a Controller.
This is the execute function I have
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$entityManager = $container->get('doctrine')->getManager();
$mailer = $container->get('mailer');
$transport = $container->get('swiftmailer.transport.real');
$things = $container->get('mike.stuff.service')->getThings();
foreach ($things as $thing) {
$recipients = array($thing->getPerson()->getEmail() => $thing->getPerson()->getName());
$message = sprintf('Hello %s'.PHP_EOL.PHP_EOL.'This is an alert regarding %s',
$thing->getPerson()->getName(),
$thing->getReferenceNumber());
$email = \Swift_Message::newInstance()
->setSubject('Alert')
->setFrom('noreply#mydomain.com')
->setTo($recipients)
->setBody($message);
$mailer->send($email);
}
}
// Flush the mailer transport
$spool = $mailer->getTransport()->getSpool();
$sent = $spool->flushQueue($transport);
echo 'I sent ' . $sent;
}
When I run the command the output is "I sent 1", so it looks like it has worked. But /var/log/mail.log does not have anything added to it (so of course I don't receive an email).

Commands are run in the dev environment by default, so if you have different configs for dev and prod environments, you will need to run your command in the prod environment (with --env=prod)

Related

How to send mail in simple_jwt_login wordpress plugin hook?

I am using this plugin for Wordpress:
https://simplejwtlogin.com/docs/hooks/#1-simple_jwt_login_login_hook
When someone logs in on my external app through rest api, I want wordpress to send email by triggering the hook:
functions.php
add_action('simple_jwt_login_login_hook', 'my_test');
function my_test() {
$to = 'you#yourmail.com';
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "me#email.com";
$headers[] = 'Content-type: text/html; charset=utf-8';
$headers[] = "From:" . "me#email.com";
wp_mail($to,$subject,$message,$headers);
}
I also have "Easy SMTP" plugin installed and working properly (wp_mail() should go through my smtp mail)
I don't see any errors in error.log, nor anything in mail.log. Do you think the hook is getting triggered or not?
make sure you enable simple_jwt_login_login_hook
to test the hook, just throw an error in it and see if its captured on error log
like this
add_action('simple_jwt_login_login_hook', function( $user ) {
throw new Exception('I\'m here mortals');
}, 11 , 1);
or via init
add_action('init', function() {
add_action('simple_jwt_login_login_hook', function( $user ) {
throw new Exception('I\'m here mortals');
}, 11, 1);
}, 99)

Symfony: Webhook End Point Problems

I am having trouble with Webhook Endpoints.
#[Route("/web_hook", name: 'web_hook')]
public function webhook(Request $request)
{
$data = json_decode($request->getContent(), true);
if ($data === null){
throw new \Exception('bad bad');
}
$txt = 'samle of some text text text';
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($myfile, $txt);
fwrite($myfile, $data->id);
fclose($myfile);
$response = new Response();
$response->setStatusCode(200);
return $response;
}
I am having 0 luck getting it to work, I am sending a POST request to it VIA Postman and it keeps coming back with error 500.
When I visit then URL it gives me this error
"Cannot autowire argument $request of "App\Controller\WebHookController::webhook()": it references class "Symfony\Component\HTTPFoundation\Request" but no such service exists.
"
I based this method off of
https://symfonycasts.com/screencast/stripe-level2/webhook-endpoint-setup.
any ideas on what im doing wrong would be greatly appreciated.
if you get error message like this
Cannot autowire argument $request of
"App\Controller\WebHookController::webhook()": it references class
"Symfony\Component\HTTPFoundation\Request" but no such service exists.
mean this service is not available. please try install http-foundation component first.
composer require symfony/http-foundation
and try to change use Symfony\Component\HTTPFoundation\Request to use Symfony\Component\HttpFoundation\Request

Call a command within a listener

I have a pretty complex command (not written by me) in my symfony API to send notifications, and I would like to have it run everytime a PostPersist event happens.
For this, I've set up a listener triggered by the PostPersist event and this part works perfectly. However, I can't manage to launch the command. I first tried to launch it like I did in a controller with the following piece of code:
$kernel = $this->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput(array(
'command' => 'acme:send-notifications',
));
// You can use NullOutput() if you don't need the output
$output = new NullOutput();
$application->run($input, $output);
return new Response("");
but of course, it doesn't work in a Listener, since I can't get the kernel
So I tried to add the command to the services:
command.send-notifications:
class: WD\ApiBundle\Command\SendNotificationsCommand
tags:
- { name: 'console.command', command: 'acme:send-notifications' }
and then call it this way:
$output = new NullOutput();
$this->sendNotifCommand->execute(null, $output);
but then I get the following error message:
The container cannot be retrieved as the application instance is not yet set.
I have to admit I don't quite understand what it means. Also, I must confess this part of symfony (listeners, commands) are quite new to me and I don't even know if I'm doing it the right way, or if there is a better system to send notifications everytime a persist happens in a specific entity...
Never tried it in a listener but you can try to launch your command with a Process :
$process = new Process("cd " . $this->projectDir . "; php bin/console YOUR_COMMAND_NAME");
$process->start();

Swiftmailer not sending emails to the delivery_addresses in dev mode

I am having trouble sending emails to the email address specified in config_dev.yml:
swiftmailer:
delivery_addresses: ['dev#example.com']
I am trying to send from a console command:
php app/console ecard:task:run send --env=dev
Console command code:
...
foreach ($emailQueue as $item) {
$transport = Swift_SmtpTransport::newInstance($item['smtp_host'])
->setPort($item['smtp_port'])
->setUserName($item['smtp_login'])
->setPassword($item['smtp_password'])
->setEncryption('ssl');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance()
->setSubject($item['email_subject'])
->setFrom($item['email_from'], $item['email_from_name'])
->setTo($item['email_to'])
->addPart($item['email_template'], 'text/html');
$ret = $mailer->send($message, $failedRecipients);
....
}
The emails are sent to the real recipient addresses, and not the one I specified in config_dev.yml.
If I dump $this->getContainer()->getParameter('kernel.environment') in code, its 'dev'.
I don't get the $mailer this way: $this->getContainer()->get('mailer'), because I want specify/change the smtp settings in cycle - the config is stored in the database, and not in the parameters.yml. Maybe this is the problem?
(Symfony version 2.8.16, Swiftmailer 5.4.5)
If you get your mailer with:
$mailer = Swift_Mailer::newInstance($transport);
then it ignores all the parameters specified in config.yml.
In this case you must set the destination address in code, as you do with the other mailer parameters, something like:
$message = Swift_Message::newInstance()
->setSubject($item['email_subject'])
->setFrom($item['email_from'], $item['email_from_name'])
->setTo($this->getContainer()->getParameter('swiftmailer.delivery_addresses')?:$item['email_to'])
->addPart($item['email_template'], 'text/html');

Drupal 7 - Emails are not going out

I'm in need of help for a custom form in which emails are not being sent.
Context: Within Drupal, I have installed the following modules: PHPMailer, SMTP Authentication Support, Mail System and Mime Mail.
Configuring the above modules you have the option to test your configurations and when preforming such tests emails are being sent properly. However, when writing a module for a form, emails are not being sent.
I don't get any type of erros nor message. I just don't get the email.
Here is the snipped of code that I'm using:
function application_form_submit($form, &$form_state) {
$subject = "testing web form";
$body = array();
$body[] = "Mail body";
$send = FALSE;
$mail_message = drupal_mail('application', 'apply-jobs', 'email#gmail.com', language_default(), $params = array(), $from = 'user#test.com', $send);
$mail_message['subject'] = $subject;
$mail_message['body'] = $body;
$mail_system = drupal_mail_system('application', 'apply-jobs');
$mail_message = $mail_system->format($mail_message);
$mail_message['result'] = $mail_system->mail($mail_message);
}
Suggestions?
You've got an odd way of defining optional parameters. This bit:
$from = 'user#test.com'
will evaluate to... nothing
Try changing your drupal_mail() call like this:
$mail_message = drupal_mail('application', 'apply-jobs', 'email#gmail.com', language_default(), array(), 'user#test.com', $send);
I found the solution to my question. The solution is:
The Mail System module allows one to Configure Mail System settings per module, which means that I had to create new mail system for my customized module an indicate the mail system that I want to use. After I did this, all my email are being sent without any problems.
Hope this helps someone, as there is very little information about this.
Thank you all.

Resources