简体   繁体   中英

Is there a way to do an app-based round-robin rotation of SMTP servers?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM