0

I am using the SMTPClient class which uses the following in the app.config

  <system.net>
    <mailSettings>
      <smtp from="mailer &lt;no_reply@mysite.com&gt;">
        <network defaultCredentials="true" host="192.168.1.101" port="25"/>
      </smtp>
    </mailSettings>
  </system.net>

Is there a way to do add more SMTP servers (say 4 servers) and get the code to do a round-robin on which SMTP server to use?

For example, I have 4 SMTP servers: 192.168.1.101, 192.168.1.102, 192.168.1.103, 192.168.1.104, And I have 8 e-mails to send.

What I hope to achieve is:

Mail 1 sent using 192.168.1.101
Mail 2 sent using 192.168.1.102
Mail 3 sent using 192.168.1.103
Mail 4 sent using 192.168.1.104
Mail 5 sent using 192.168.1.101
Mail 6 sent using 192.168.1.102
Mail 7 sent using 192.168.1.103
Mail 8 sent using 192.168.1.104
Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
Rafferty
  • 937
  • 1
  • 9
  • 16
  • 2
    Is there a reason you don't want to use a name instead of an IP and use DNS for the round-robin selection? – pvanhouten Oct 17 '12 at 04:00
  • Hi, we are just considering both options - either do it on the app side or set up a DNS server just for this requirement. Once we know the effort and pact of both options do we decide on which approach to take. – Rafferty Oct 17 '12 at 05:33

1 Answers1

0

Implementing something to do this would be fairly trivial (and there's a million ways to approach this, so I'm sure someone has a better way), but this would be a quick / easy way to get the effect you're looking for. I'm assuming you have a way of making this into a persistent object in your app.

public class SmtpQueue
{
    private Queue<string> _queue;

    public SmtpQueue(string[] ips)
    {
        _queue = new Queue<string>();

        LoadIps(ips);
    }

    private void LoadIps(string[] ips)
    {
        // load the ips
        foreach (string ip in ips)
            _queue.Enqueue(ip);
    }

    public string GetNext()
    {
        string nextIp = _queue.Dequeue();
        _queue.Enqueue(nextIp);
        return nextIp;
    }
}

You would consume it like this:

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Host = mySmtpQueueInstance.GetNext();

Whatever you end up doing, don't over-complicate it. Generally this would be something you'd accomplish with DNS and I'd recommend that approach if possible.

pvanhouten
  • 762
  • 10
  • 27
  • Hi, thanks for the suggestion with actual code. I guess I was not able to compose the question really well. I'm aware that we can change the .Host property via code, but does this mean that I can't use the existing schema in the app.config to have 4 configurable hosts? In this case, then the simplest approach would be to just add new AppSetting keys and the rest is just code. Correct? – Rafferty Oct 18 '12 at 05:49
  • Yes, that is correct. That's why I'd go the DNS approach so there's no code to write. – pvanhouten Oct 18 '12 at 14:25