How to programmatically retrieve smtp server details from web.config - c#

I have the following SMTP details stored in web.config
<system.net>
<mailSettings>
<smtp from="isds#ixtent.com">
<network host="mail.domain.com" port="25" userName="username" password="password" defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
How can I retrieve these values from within a c# class.

Configuration configurationFile = WebConfigurationManager
.OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile
.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;
string password = mailSettings.Smtp.Network.Password;
string username = mailSettings.Smtp.Network.UserName;
}

If you need to send email with this mail-server-details you don't need to read the settings and apply. These settings are applied implicitly in the application.
If you are reading it for any other reason I was about to write something similar to Darin's answer. But just as I was writing I found he answered so please refer to his answer if you actually need to read. :)

What about:
string fullpath = #"C:\FullPath\YourFile.config";
string configSection = "system.net/mailSettings";
Configuration config = ConfigurationManager.OpenExeConfiguration(fullpath);
MailSettingsSectionGroup settings =
config.GetSectionGroup(configSection) as MailSettingsSectionGroup;

Related

Moving email setting to web config

I am try to move my email settings to web config, but i don't know how to call the setting from web config.
This is my newpassword web-config setting:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from=""testo" <admin#test.com>" >
<network host="mail.test.com" userName="admin#test.com" password="waiff75E-" port="25"/>
</smtp>
</mailSettings>
</system.net>
And this is my previous code
const string username = "test#smartguroo.com";
const string password = "password";
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("admin#test.com", loggedinUser.Text + "test");
smtpclient.Host = "mail.test.com";
smtpclient.Port = 25;
mail.From = fromaddress;
mail.To.Add(userEmail.Text);
mail.Subject = ("New post on your wall from " + loggedinUser.Text + " ");
// mail.Attachments.Add(new mail);
mail.IsBodyHtml = true;
mail.Body = "";
Remove the following lines lines since you want your settings in the web.config file to drive it from the configuration point of view.
smtpclient.EnableSsl = false;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
And just call the Send method on the SmtpClient
smtpclient.Send(mail);
All the previous concerns are configured into your web.config file, as you have done so. (Copied verbatim)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from=""testo" <admin#test.com>" >
<network host="mail.test.com" userName="admin#test.com" password="password" port="25"/>
</smtp>
</mailSettings>
</system.net>
In your webconfig
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<!-- Markup removed for clarity. -->
<add key="mailAccount" value="xyz" />
<add key="mailPassword" value="password" />
</appSettings>
<system.web>
Reference in c# via
var credentials = new NetworkCredential(
ConfigurationManager.AppSettings["mailAccount"],
ConfigurationManager.AppSettings["mailPassword"]
);
This was using this identity tutorial

How to read system.net/mailSettings/smtp from Web.config

This is my web.config mail settings:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="smthg#smthg.net">
<network defaultCredentials="true" host="localhost" port="587" userName="smthg#smthg.net" password="123456"/>
</smtp>
</mailSettings>
</system.net>
and here's how I try to read the values from web.config
var smtp = new System.Net.Mail.SmtpClient();
var credential = new System.Net.Configuration.SmtpSection().Network;
string strHost = smtp.Host;
int port = smtp.Port;
string strUserName = credential.UserName;
string strFromPass = credential.Password;
But credentials are always null. How can i access these values?
Since no answer has been accepted, and none of the others worked for me:
using System.Configuration;
using System.Net.Configuration;
// snip...
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string username = smtpSection.Network.UserName;
It is not necessary to use the ConfigurationManagerand get the values manually. Simply instantiating an SmtpClient is sufficient.
SmtpClient client = new SmtpClient();
This is what MSDN says:
This constructor initializes the Host, Credentials, and Port properties for the new SmtpClient by using the settings in the application or machine configuration files.
Scott Guthrie wrote a small post on that some time ago.
By using the configuration, the following line:
var smtp = new System.Net.Mail.SmtpClient();
Will use the configured values - you don't need to access and assign them again.
As for the null values - you are trying accessing the configuration values incorrectly. You are just creating an empty SmtpSection instead of reading it from configuration.
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("<the section name>");
var credentials == smtpSection.Network;
I think if you have defaultCredentials="true" set you will have the credentials = null as you are not using them.
Does the email Send when you call the .Send method?
So
This is my web config mail settings:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="smthg#smthg.net">
<network defaultCredentials="false" host="localhost" port="587"
userName="smthg#smthg.net" password="123456"/>
</smtp>
</mailSettings>
</system.net>
and this is cs
SmtpClient smtpClient = new SmtpClient();
string smtpDetails =
#"
DeliveryMethod = {0},
Host = {1},
PickupDirectoryLocation = {2},
Port = {3},
TargetName = {4},
UseDefaultCredentials = {5}";
Console.WriteLine(smtpDetails,
smtpClient.DeliveryMethod.ToString(),
smtpClient.Host,
smtpClient.PickupDirectoryLocation == null
? "Not Set"
: smtpClient.PickupDirectoryLocation.ToString(),
smtpClient.Port,
smtpClient.TargetName,
smtpClient.UseDefaultCredentials.ToString)
);
//You can access the network credentials in the following way.
//Read the SmtpClient section from the config file
var smtp = new System.Net.Mail.SmtpClient();
//Cast the newtwork credentials in to the NetworkCredential class and use it .
var credential = (System.Net.NetworkCredential)smtp.Credentials;
string strHost = smtp.Host;
int port = smtp.Port;
string strUserName = credential.UserName;
string strFromPass = credential.Password;
make sure you have reference to System.Net in your application
Set defaultCredentials="false", because when it's set to true, no credentials are used.

Code runs fine on localhost but doesn't execute on gatorhost

I wrote a small website in VWD. I am running it on my home machine using the localhost features of VWD. It runs flawlessly.
Now the backstory. I had a linux server with gatorhost. I had them switch my domain and my server type to windows because i decided to learn asp.net(c#). I had a million problems with them hours on the phone. Issues with unable to connect when you search for my domain and my e-mail features and ftp features where all messed up took them hours to figure it out in multiple calls and tickets.
So now i think i got it all working i load my site through VWD onto my server (www.contentiousweb.com) All of my front end code works fine as far as form validation and links.
When i hit my submit buttons that would execute my c# code nothing happens at all. not a thing. When the forms are filled out wrong the validation works. I got no errors or anything. i like dont know where to start. Is it my code there server how much can i rely on VWD in being right because i cannot rely on my self lol.
Webconfig file. (i swapped out my pw and e-mail)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="Ralph <********#hotmail.com>">
<network enableSsl="true" host="smtp.live.com" userName="*************#hotmail.com" password="***********" port="587" />
</smtp>
</mailSettings>
</system.net>
Bellow is the button.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string fileName = Server.MapPath("_TextFiles/ContactForm.txt");
string mailBody = File.ReadAllText(fileName);
mailBody = mailBody.Replace("##Name##", nameBox.Text);
mailBody = mailBody.Replace("##Email##", emailBox.Text);
mailBody = mailBody.Replace("##Subject##", subBox.Text);
mailBody = mailBody.Replace("##Message##", MsgField.Text);
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Response from Contact Page";
myMessage.Body = mailBody;
myMessage.From = new MailAddress("******", "Contact");
myMessage.To.Add(new MailAddress("******", " Server"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMessage);
Message.Visible = true;
ContactTable.Visible = false;
System.Threading.Thread.Sleep(5000);
}
}
}
Any help would be greatly appresciated. i am new and learning but with my experince and problems with hostgator i think that it is something on there end because everything else has been. i am clueless.
Please let me know if there is anymore information i can provide. Thank you for any help
In my own troubleshooting i found this error just now using mozila dev tools.
[18:03:28.399] Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500 # http://contentiousweb.com/ScriptResource.axd?d=EJBSV2JIVC3wCtbtVqDWEZfeOsqUeA-l1kZnjjZKvx15e0cjnzPdj4H78hvszmtfrIhAM96VdUstdDjn1xGAbsydMzIjEQeNWDOz2tihnjEjxDW5esVemHLoHR01oIyUBoZTNPd7atx4-EPBnuVlWYbQIeLdoH_eBXy1j9kav6ac2ptv4Cl8sraaDBGXntVH0&t=ffffffff940d030f:1507
Thanks for any help i am still looking for answers my self.
I got it going. After talking with gatorhost on the phone for four hours we determined that the smtp information they had provided me would not work. They had me change my host to
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="localhost" userName="*************#hotmail.com" password="***********" port="25" />
</smtp>
</mailSettings>
</system.net>
And now it all works no errors. Thank you everyone who helped with ideas.
I don't see in your code assigning the port number or credentials?
This code should work
// SMTP options
string Host = "smtp.mail.emea.microsoftonline.com";
Int16 Port = 587;
bool SSL = true;
string Username = "myname#mydomain.com";
string Password = "mypassword";
// Mail options
string To = "reciever#recieverdomain.com";
string From = "myname#mydomain.com";
string Subject = "This is a test";
string Body = "It works!";
MailMessage mm = new MailMessage(From, To, Subject, Body);
SmtpClient sc = new SmtpClient(Host, Port);
NetworkCredential netCred = new NetworkCredential(Username, Password);
sc.EnableSsl = SSL;
sc.UseDefaultCredentials = false;
sc.Credentials = netCred;
try
{
Console.WriteLine("Sending e-mail message...");
sc.Send(mm);
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}

How to get the HostName, Ip of the machine hosting the asp.net application

How can i get the LocalhostName, Ip of the machine hosting the Application. For development it would be localhost for deployment something different. This i need to initialize the SmtpClient to send emails through application
SmtpClient emailClient = new SmtpClient("host","port");//port is optional
i am looking for a permanent solution, no workarounds and no sniffing from response, request and this could be spoofed[hope i am not crazy because no one can spoof the servers data in headers can they?]
If you want to configure SmtpClient class, you should have a look at the system.net > mailsettings entry of the web.config : http://msdn.microsoft.com/en-us/library/w355a94k.aspx
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>
And instanciate the StmpClient with parameterless constructor
var client = new SmtpClient();
if you use
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
and
public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
it should return something like
IsLocalIpAddress("localhost"); // true (loopback name)
IsLocalIpAddress("127.0.0.1"); // true (loopback IP)
IsLocalIpAddress("MyNotebook"); // true (my computer name)
IsLocalIpAddress("192.168.0.1"); // true (my IP)
IsLocalIpAddress("NonExistingName"); // false (non existing computer name)
IsLocalIpAddress("99.0.0.1"); // false (non existing IP in my net)
this can be simply modified to return the address you need

Email sending error in ASP.NET using C#

This is the code for email sending, but it gives error in try block:
protected void Page_Load(object sender, EventArgs e)
{
EmailUtility email = new EmailUtility();
email.Email = new MailMessage();
string body = email.GetEmailTemplate(Server.MapPath("~/EmailTemplates"), "test.htm");
EmailMessageToken token = new EmailMessageToken();
token.TokenName = "$Name$";
token.TokenValue = "Ricky";
EmailMessageTokens tokens = new EmailMessageTokens();
tokens.Add(token);
//av.LinkedResources.Add(lr);
email.Email.Body = email.ReplaceTokens(body, tokens);
email.Email.To.Add(new MailAddress("sahil4659#gmail.com"));
email.Email.IsBodyHtml = true;
email.Email.From = new MailAddress("sahil4659#gmail.com");
email.Email.Subject = "Hello from bootcamp";
email.SMTP.Host = ConfigurationManager.AppSettings["SMTPServer"];
try
{
email.SMTP.Send(email.Email);
Response.Write("Email sent !");
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
The error is:
at System.Net.Mail.IisPickupDirectory.GetPickupDirectory()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at _Default.Page_Load(Object sender, EventArgs e) in c:\Users\Sahil\Desktop\Csharp Email Code(2)\Test website\EmailTest.aspx.cs:line 38
I'm going to read your mind and assume that you're seeing System.Net.Mail.SmtpException: Cannot get IIS pickup directory. Googling around, I see references to SMTP configuration you'll need in your web configuration. Your mail server may require credentials, so you might need something like this:
<system.net>
<mailSettings>
<smtp from="fromaddress">
<network defaultCredentials="true"
host="smtpservername" port="smtpserverport"
userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
... in your web.config. Essentially, configure your web app to be able to talk with the SMTP server.
See this thread for more reference, and here's relevant MSDN documentation.

Categories