Monday, June 8, 2009

How to read email address, host, port number from smtp settings section of web.config file in

How can I read the email address, smtp host, port number from my mail settings section of the web.config file in an web application? Yeah, we can specify an email address in the mail settings section of web.config file and read it from web page in the time of sending an email. We can also read the smtp host and port number which is necessary while sending email from an web page. I have already discussed: How to send email from web page. So here I would just put the coding to read email address, host, port number from mail settings section of web.config file in web application.

Let's look into the mail setting portion of a web.config file.




<network host="mymailhostaddress" port="25"/>




While sending an email, we need from, to email addresses and an smtp client also. So the code snippet below puts them together.

using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

//the method to send email
public void SendMail()
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("") as MailSettingsSectionGroup;
SmtpSection smtpSection = mailSettings.Smtp;
//read the from email of the web.config file
string fromEmail = smtpSection.From;
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;

//..other code follows from here
//that sends the email

//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress(fromEmail), new MailAddress(""));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient(host, port);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
catch (Exception ex)
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;

Using the code above, we easily accessed the important information from mail settings section of the web.config file. Please note again that I have just put the coding of reading information form web.config file. You can learn from here to Send Email in web page so that you can combine what this article provides with sending email in web application. Happy Programming!

kick it on Shout it pimp it


Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles