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
I had the same need and the marked answer worked for me.
I made these changes in the
web.config:
<configSections>
<sectionGroup name="mailSettings2">
<section name="noreply" type="System.Net.Configuration.SmtpSection"/>
</sectionGroup>
<section name="othersection" type="SomeType" />
</configSections>
<mailSettings2>
<noreply deliveryMethod="Network" from="noreply@host.com"> // noreply, in my case - use your mail in the condition bellow
<network enableSsl="false" password="<YourPass>" host="<YourHost>" port="25" userName="<YourUser>" defaultCredentials="false" />
</noreply>
</mailSettings2>
... </configSections>
Then, I have a thread that send the mail:
SomePage.cs
private bool SendMail(String From, String To, String Subject, String Html)
{
try
{
System.Net.Mail.SmtpClient SMTPSender = null;
if (From.Split('@')[0] == "noreply")
{
System.Net.Configuration.SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings2/noreply");
SMTPSender = new System.Net.Mail.SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
SMTPSender.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
Message.From = new System.Net.Mail.MailAddress(From);
Message.To.Add(To);
Message.Subject = Subject;
Message.Bcc.Add(Recipient);
Message.IsBodyHtml = true;
Message.Body = Html;
Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
SMTPSender.Send(Message);
}
else
{
SMTPSender = new System.Net.Mail.SmtpClient();
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
Message.From = new System.Net.Mail.MailAddress(From);
SMTPSender.EnableSsl = SMTPSender.Port == <Port1> || SMTPSender.Port == <Port2>;
Message.To.Add(To);
Message.Subject = Subject;
Message.Bcc.Add(Recipient);
Message.IsBodyHtml = true;
Message.Body = Html;
Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
SMTPSender.Send(Message);
}
}
catch (Exception Ex)
{
Logger.Error(Ex.Message, Ex.GetBaseException());
return false;
}
return true;
}
Thank you =)
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:
<configuration>
<configSections>
<sectionGroup name="mailSettings">
<section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
<section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
<section name="smtp_3" type="System.Net.Configuration.SmtpSection"/>
</sectionGroup>
</configSections>
<mailSettings>
<smtp_1 deliveryMethod="Network" from="mail1@temp.uri">
<network host="..." defaultCredentials="false"/>
</smtp_1>
<smtp_2 deliveryMethod="Network" from="mail2@temp.uri">
<network host="1..." defaultCredentials="false"/>
</smtp_2>
<smtp_3 deliveryMethod="Network" from="mail3@temp.uri">
<network host="..." defaultCredentials="false"/>
</smtp_3>
</mailSettings>
</configuration>
Then in code:
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_2");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_3");
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
SmtpClient smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
smtpClient.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
I ended up building my own custom configuration loader that gets used in an EmailService class. Configuration data can be stored in web.config much like connection strings, and pulled by name dynamically.
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:
System.Net.Mail.MailMessage mail = null;
System.Net.Mail.SmtpClient smtp = null;
mail = new System.Net.Mail.MailMessage();
//set the addresses
mail.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["Email1"]);
mail.To.Add("someone@example.com");
mail.Subject = "The secret to the universe";
mail.Body = "42";
//send the message
smtp = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings["YourSMTPServer"]);
//to authenticate, set the username and password properites on the SmtpClient
smtp.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["EmailUsername1"], System.Configuration.ConfigurationManager.AppSettings["EmailPassword1"]);
smtp.UseDefaultCredentials = false;
smtp.Port = System.Configuration.ConfigurationManager.AppSettings["EmailSMTPPort"];
smtp.EnableSsl = false;
smtp.Send(mail);
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
/// <summary>
/// Overrides the default SMTP Client class to go ahead and default the host and port to Mandrills goodies.
/// </summary>
public class MandrillSmtpClient : SmtpClient
{
public MandrillSmtpClient( string smtpUsername, string apiKey, string host = "smtp.mandrillapp.com", int port = 587 )
: base( host, port )
{
this.Credentials = new NetworkCredential( smtpUsername, apiKey );
this.EnableSsl = true;
}
}
Here's an example of how to call this:
[Test]
public void SendMandrillTaggedEmail()
{
string SMTPUsername = _config( "MandrillSMTP_Username" );
string APIKey = _config( "MandrillSMTP_Password" );
using( var client = new MandrillSmtpClient( SMTPUsername, APIKey ) ) {
MandrillMailMessage message = new MandrillMailMessage()
{
From = new MailAddress( _config( "FromEMail" ) )
};
string to = _config( "ValidToEmail" );
message.To.Add( to );
message.MandrillHeader.PreserveRecipients = false;
message.MandrillHeader.Tracks.Add( ETrack.opens );
message.MandrillHeader.Tracks.Add( ETrack.clicks_all );
message.MandrillHeader.Tags.Add( "NewsLetterSignup" );
message.MandrillHeader.Tags.Add( "InTrial" );
message.MandrillHeader.Tags.Add( "FreeContest" );
message.Subject = "Test message 3";
message.Body = "love, love, love";
client.Send( message );
}
}