Reputation: 767
I have a problem sending my emails with Symfony.
swiftmailer.yaml
swiftmailer:
default_mailer: gmail_api
mailers:
gmail_api:
transport: gmail_api
As you can see I'm not using the spooling.
My emails are sent correctly from Controller but not from Command.
From Controller, send() return 1 and I receive the email.
namespace App\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
class CRUDController extends Controller
{
private $mailer;
...
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
...
}
private function sendEmail($object, $identifiant, $type)
{
$message = (new \Swift_Message('xxx ' . $identifiant))
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody(
$this->renderView(
...
),
'text/html'
)
->attach(\Swift_Attachment::fromPath('xxx');
try {
$logger = new \Swift_Plugins_Loggers_ArrayLogger();
$this->mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
$numSent = $this->mailer->send($message);
if ($numSent < 1) {
$this->addFlash('sonata_flash_error', 'Fail to send e-mail');
} else {
if (method_exists($object, 'getMailing')
&& method_exists($object, 'setMailing')) {
$object->setMailing($object->getMailing() + 1);
$this->em->persist($object);
$this->em->flush();
}
}
} catch (\Swift_TransportException $e) {
$this->addFlash('sonata_flash_error', $e->getMessage());
}
dump($logger->dump());
exit();
}
\Swift_Plugins_Loggers_ArrayLogger give me:
++ Starting Swift_Transport_EsmtpTransport ... << 250 OK
From Command, send() return 0 and I don't receive the email.
class ExempleCommand extends Command
{
private $mailer;
...
public function __construct(\Swift_Mailer $mailer)
{
parent::__construct();
$this->mailer = $mailer;
...
}
protected function sendNotificationMail(OutputInterface $output, $subject, $body)
{
$logger = new \Swift_Plugins_Loggers_ArrayLogger();
$this->mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
$message = (new \Swift_Message($subject))
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody(
$this->twig->render(
...
),
'text/html'
);
try {
$output->write("\n" . $this->mailer->send($message));
} catch (\Swift_TransportException $e) {
echo $e->getMessage();
}
$output->write($logger->dump());
}
\Swift_Plugins_Loggers_ArrayLogger give me:
++ Starting App\Service\Email\GmailApiTransport ++ App\Service\Email\GmailApiTransport started
Why it's not starting with Swift_Transport_EsmtpTransport within Command?
Upvotes: 1
Views: 412
Reputation: 69
I'm not sure how it work with Symfony 4, never had to send mail via command since a while but on Symfony 2, when using a command you had to start a new instance of the mailer. So maybe you can try to change your constructor to
public function __construct(\Swift_SmtpTransport $transport)
{
parent::__construct();
$this->mailer = new \Swift_Mailer($transport);
}
(Sorry, i don't have the privilege to simply put a comment yet)
Upvotes: 1