I am building an app that needs to dynamically/programatically know of and use different SMTP settings when sending email.
I'm used to using the system.net/mailSettings approach, but as I understand it, that only allows one SMTP connection definition at a time, used by SmtpClient().
However, I need more of a connectionStrings-like approach, where I can pull a set of settings based on a key/name.
Any recommendations? I'm open to skipping the tradintional SmtpClient/mailSettings approach, and I think will have to...
It seems that you can initialize using different SMTP strings.
SmtpClient client = new SmtpClient(server);
http://msdn.microsoft.com/en-us/library/k0y6s613.aspx
I hope that is what you are looking for.
Just pass in the relevant details when you are ready to send the mail, and store all of those settings in your app setttings of web.config.
For example, create the different AppSettings (like "EmailUsername1", etc.) in web.config, and you will be able to call them completely separately as follows:
This is how i use it and it works fine for me (settings are similar to Mikko answer):
First set up config sections:
Then it would be the best to create a some sort of wrapper. Note that most of code below was taken from .NET source code for SmtpClient here
}
Then simply send email:
new CustomSmtpClient("mailings").Send(new MailMessage())
I needed to have different smtp configurations in the web.config depending on the environment: dev, staging and production.
Here's what I ended up using:
In web.config:
Then in code:
This may or may not help someone but in case you got here looking for Mandrill setup for multiple smtp configurations I ended up creating a class that inherits from the SmtpClient class following this persons code here which is really nice: https://github.com/iurisilvio/mandrill-smtp.NET
Here's an example of how to call this: