Swiftmailer Multiple SMTP

Swift Mailer is a fantastic library for sending email with php. Discuss this library or ask any questions about it here.

Moderators: Chris Corbyn, General Moderators

Post Reply
rorossf
Forum Newbie
Posts: 2
Joined: Tue Jan 13, 2015 12:37 am

Swiftmailer Multiple SMTP

Post by rorossf »

I'm using the PHP Swiftmailer package and was looking for a way to use multiple SMTP servers. I found the Swift LoadBalance Transport and from what I read this would round robin between SMTP connection. However, I have two SMTP servers with each one is running a different mailserver domain. Is there a way to change the ->setFrom(MAIL_FROM) based on the SMTP server transport instance being used?

Ex. $transport1 uses a FROM: company@domain1.com $transport2 uses a FROM: company@domain2.com

Code: Select all

// POINT of this sample
$transport1 = Swift_SmtpTransport::newInstance(SMTP_HOST, SMTP_PORT);
$transport2 = Swift_SmtpTransport::newInstance(SMTP_HOST2, SMTP_PORT2);
$transport = Swift_LoadBalancedTransport::newInstance([
$transport1,
$transport2,
]);

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message
->setFrom(MAIL_FROM)
->setSubject('LoadbalancedTransport sample')
->setBody('This is a mail.');
$recipients = [MAIL_TO, MAIL_TO2];
$total = 0;


foreach ($recipients as $recipient) {
$message->setTo($recipient);
$result = $mailer->send($message);
$total += $result;
}
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Swiftmailer Multiple SMTP

Post by Weirdan »

It should be pretty easy with a plugin handling 'beforeSendPerformed' event (you could base it on ImpersonatePlugin). It receives Swift_Events_SendEvent, from which you could get both transport being used to send the message and the message itself, so you could modify the originating address accordingly.
rorossf
Forum Newbie
Posts: 2
Joined: Tue Jan 13, 2015 12:37 am

Re: Swiftmailer Multiple SMTP

Post by rorossf »

Weirdan wrote:It should be pretty easy with a plugin handling 'beforeSendPerformed' event (you could base it on ImpersonatePlugin). It receives Swift_Events_SendEvent, from which you could get both transport being used to send the message and the message itself, so you could modify the originating address accordingly.
Thank you very much. Starting to understand how to approach this, the only question I have is how would I get the transports being used to send the message.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Swiftmailer Multiple SMTP

Post by Weirdan »

$event->getTransport() where $event is an instance of Swift_Events_SendEvent passed in to the event handler method.
Post Reply