Symfony 3.3 и Swiftmailer - почта, созданная и отправленная контроллером, отложенная сервером
Я пытаюсь использовать Swiftmailer для отправки электронной почты с веб-сайта. Письма продолжают откладываться, потому что Swiftmailer пытается использовать IP-адрес своего сервера, а не localhost в качестве реле:
Aug 2 14:18:28 picus sm-mta[21171]: v72IIS0I021171: from=<[email protected]>, size=347, class=0, nrcpts=1, msgid=<[email protected]>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Aug 2 14:18:28 picus sm-mta[21173]: v72IIS0I021171: to=<[email protected]>, delay=00:00:00, xdelay=00:00:00, mailer=esmtp, pri=120347, relay=example.com. [my.servers.ip.address], dsn=4.0.0, stat=Deferred: Connection refused by example.com.
Код, конфиг и параметры контроллера My Symfony -
Соответствующий код контроллера:
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$this->addFlash('success', 'Message sent successfully');
$data['message'] = str_replace("\n.", "\n..", $data['message']);
$mail = (new \Swift_Message())
->setSubject("[From My Website] - {$data['subject']}")
->setFrom($data['email'])
->setTo('[email protected]')
->setBody("{$data['name']} wrote the following message:\n\n{$data['message']}");
$this->get('mailer')->send($mail);
return $this->redirect($this->generateUrl('_home'));
}
config.yml
:
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
port: '%mailer_port%'
spool:
type: file
path: '%kernel.cache_dir%/swiftmailer/spool'
parameters.yml
:
parameters:
mailer_transport: sendmail
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
mailer_port: null
Что действительно расстраивает то, что если я создаю сообщение, используя bin/console swiftmailer:email:send
, а затем очищаю катушку (bin/console swiftmailer:spool:send
), она отправляется должным образом. Он только, когда я создаю и отправляю сообщение через контроллер, что есть проблема.
Что я делаю неправильно?
Ответы
Ответ 1
Ooof
Это была ошибка DNS на моей стороне, которая вызывала проблему. А именно, что я забыл указать свои записи MX на почтовые серверы Google, поэтому sendmail принимал часть example.com
адреса назначения и пытался использовать его в качестве реле smtp, хотя у меня не было настроено почтовое серверное устройство.
Извините за все ужасы. Надеюсь, мой ответ может быть полезен для других, ударяющих головой о стену.
Ответ 2
Почему вы используете Transportmail вместо транспорта SMTP?
https://swiftmailer.symfony.com/docs/sending.html
Попробуйте следующее:
config.yml
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
port: "%mailer_port%"
encryption: "%mailer_encryption%"
spool: { type: memory }
parameters.yml
parameters:
mailer_transport: smtp
mailer_host: smtp.office365.com
mailer_user: [email protected]
mailer_password: my_password
mailer_port: 587
mailer_encryption: tls
контроллер
$message = \Swift_Message::newInstance()
->setSubject('Subject')
->setFrom(array('[email protected]' => 'My name'))
->setTo(array($user->getMail()))
->setBcc(array('[email protected]', '[email protected]'))
->setBody(
$this->renderView(
'template.html.twig',
array('vars' => $vars)
),
'text/html'
);
$this->get('mailer')->send($message);
Ответ 3
Я могу предложить вам попробовать этот подход:
$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$sender = 'your_sender';
$recipient = 'your_recipient';
$title = 'your_title';
$body = 'your_message';
$charset = "UTF-8";
$email = $mailer->createMessage()
->setSubject($title)
->setFrom("$sender")
->setTo("$recipient")
->setCharset($charset)
->setContentType('text/html')
->setBody($body)
;
$send = $mailer->send($email);
$spool->flushQueue($transport);
Вы можете обернуть это в сообщение отправки простого сервиса YouMailService.
Или вы можете вставить этот код в свой контроллер. Этого будет достаточно.