Sending Emails with different SMTP Users

Silverstripe Version: 4.2.1

Is ist possible to define multiple SMTP users for different email addresses?:

as discribed here: https://docs.silverstripe.org/en/4/developer_guides/email/ I can define ONE email address and user for sending all my emails. Is it somehow possible to send emails from different addresses with different users?

```
---
Name: myemailconfig
After:
  - '#emailconfig'
---
SilverStripe\Core\Injector\Injector:
  Swift_Transport:
    class: Swift_SmtpTransport
    properties:
      Host: smtp.host.com
      Port: <port>
      Encryption: tls
    calls:
      Username: [ setUsername, ['`APP_SMTP_USERNAME`'] ]
      Password: [ setPassword, ['`APP_SMTP_PASSWORD`'] ]
      AuthMode: [ setAuthMode, ['login'] ]
```

You could define multiple Transport classes which have different users defined.

E.g.

---
Name: myemailconfig
After:
  - '#emailconfig'
---
SilverStripe\Core\Injector\Injector:
  Swift_Transport_user1:
    class: Swift_SmtpTransport
    properties:
      Host: smtp.host.com
      Port: <port>
      Encryption: tls
    calls:
      Username: [ setUsername, ['`APP_SMTP_USERNAME`'] ]
      Password: [ setPassword, ['`APP_SMTP_PASSWORD`'] ]
      AuthMode: [ setAuthMode, ['login'] ]
SilverStripe\Core\Injector\Injector:
  Swift_Transport_user2:
    class: Swift_SmtpTransport
    properties:
      Host: smtp.host.com
      Port: <port>
      Encryption: tls
    calls:
      Username: [ setUsername, ['`APP_SMTP_USERNAME2`'] ]
      Password: [ setPassword, ['`APP_SMTP_PASSWORD2`'] ]
      AuthMode: [ setAuthMode, ['login'] ]

Then in your PHP, you can use the Injector to get the appropriate SMTP configuration based on your own logic.

1 Like

Thanks. I’ll give it a try.

I’m trying to do the same thing, but struggling to work out exactly how to do this part.

I presume I need to selectively tell Injector to use either Swift_Transport_user1 or Swift_Transport_user2 class instead of SilverStripe\Control\Email\Mailer, at the point of sending the email? But I can only find instructions for how to do within the yml file.

I’m curious about this too. I guess you would have to use the Config API since Email::send() uses Injector to grab a Mailer, so you can’t directly access it from an Email object. Not sure of the equivalent PHP but I think you would need to effectively change it to:

SilverStripe\Core\Injector\Injector:
  Swift_Mailer:
    constructor:
      - '%$Swift_Transport_user2'

then send you email, then revert it back to whatever it was.

BTW, this is more for the OP than you and might not work for your use case, but if you are able to use a transactional email product like MailGun or PostMark, those typically let you send from any email address on a domain you have verified. The Username is incidental - it might be an email address or an API key, but the email is sent from whetever you specify in $email->setFrom(). So normally in that setup, one Transport is enough.