How do I set fallback, for swift mailer, and test my fallback code is working?. I got this standart code from the howto.
$transport = Swift_SmtpTransport::newInstance(SMTP_HOST, SMTP_PORT, 'tls')
->setUsername(SMTP_USERNAME)
->setPassword(SMTP_PASSWORD)
;
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('S5_Dagsrapport_' . $dato1)
->setFrom(array($from => 'S5'))
->setTo(array($to => $navn))
->setBody($body, 'text/html')
->addPart($body, 'text/html')
->attach(Swift_Attachment::newInstance($attachment, 's5_dagsreport_' . $dato1 . '.xls', 'application/xls'))
;
// Send the message
$mailer->send($message);
if i use
if(
$mailer->send($message)){
echo "Sent
";
}else{
echo "Failed
";
}
it shows sent, but if I put wrong info , into the parameters, it does not show Failed. I have been reading that another solution is to use
Swift_Transport_FailoverTransport
but I can't find examples online, on that.
what is the easy way to make a fallback in Swift_mailer,
I can tell from the class Swift_Transport_FailoverTransport
extends.
Contains a method called setTransports
. In there you can set the transports to use when one fails. It is a bit like a chain class. The class itself is an instance of Swift_Transport
which contains multiple other transports.
Create the transports you are going to use to connect to mail servers. Then add them to an instance of Swift_Transport_FailoverTransport
. Then use that instance as your mailer transport.
For everyone who wants to know how to use this in symfony here is my solution. Create a class which extends Swift_Transport_FailoverTransport
.
namespace AppBundle\Util;
class App_Swift_Transport_FailoverTransport extends \Swift_Transport_FailoverTransport
{
/**
* @param \Swift_Mailer[] $mailers
*/
public function __construct(array $mailers)
{
parent::__construct();
/** @var \Swift_Mailer $mailer */
foreach ($mailers as $mailer) {
$this->_transports[] = $mailer->getTransport();
}
}
}
In your config.yml
under the swiftmailer
key extend your mailers:
swiftmailer:
default_mailer: default
mailers:
default:
transport: 'app_failover'
# example mailhog config
main:
disable_delivery: false
delivery_addresses: null
transport: smtp
host: 127.0.0.1
port: 1025
username: null
password: null
# example for sendgrid
fallback:
disable_delivery: false
delivery_addresses: null
encryption: 'ssl'
transport: 'smtp'
host: 'smtp.sendgrid.net'
port: '465'
username: 'apikey'
password: 'mypassword'
And last but not least inject your defined mailers in your App_Swift_Transport_FailoverTransport
constructor:
swiftmailer.mailer.transport.app_failover:
class: AppBundle\Util\App_Swift_Transport_FailoverTransport
arguments:
$mailers: ['@swiftmailer.mailer.main', '@swiftmailer.mailer.fallback']