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/mailSet
This is how i use it and it works fine for me (settings are similar to Mikko answer):
First set up config sections:
<configuration>
<configSections>
<sectionGroup name="mailSettings">
<section name="default" type="System.Net.Configuration.SmtpSection" />
<section name="mailings" type="System.Net.Configuration.SmtpSection" />
<section name="partners" type="System.Net.Configuration.SmtpSection" />
</sectionGroup>
</configSections>
<mailSettings>
<default deliveryMethod="Network">
<network host="smtp1.test.org" port="587" enableSsl="true"
userName="test" password="test"/>
</default>
<mailings deliveryMethod="Network">
<network host="smtp2.test.org" port="587" enableSsl="true"
userName="test" password="test"/>
</mailings>
<partners deliveryMethod="Network">
<network host="smtp3.test.org" port="587" enableSsl="true"
userName="test" password="test"/>
</partners>
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
public class CustomSmtpClient
{
private readonly SmtpClient _smtpClient;
public CustomSmtpClient(string sectionName = "default")
{
SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("mailSettings/" + sectionName);
_smtpClient = new SmtpClient();
if (section != null)
{
if (section.Network != null)
{
_smtpClient.Host = section.Network.Host;
_smtpClient.Port = section.Network.Port;
_smtpClient.UseDefaultCredentials = section.Network.DefaultCredentials;
_smtpClient.Credentials = new NetworkCredential(section.Network.UserName, section.Network.Password, section.Network.ClientDomain);
_smtpClient.EnableSsl = section.Network.EnableSsl;
if (section.Network.TargetName != null)
_smtpClient.TargetName = section.Network.TargetName;
}
_smtpClient.DeliveryMethod = section.DeliveryMethod;
if (section.SpecifiedPickupDirectory != null && section.SpecifiedPickupDirectory.PickupDirectoryLocation != null)
_smtpClient.PickupDirectoryLocation = section.SpecifiedPickupDirectory.PickupDirectoryLocation;
}
}
public void Send(MailMessage message)
{
_smtpClient.Send(message);
}
}
Then simply send email:
new CustomSmtpClient("mailings").Send(new MailMessage())
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.