News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Load & Save Mail Settings in Application Configuration File using C#

Sometimes your application wants to send e-mail notifications to customers. You need to let the customers of your application to set the e-mail server that the application uses to send such e-mail notifications. As discussed in the previous article How to: Send an email Message using SMTP and C#, we save these settings in the mailSettings section under the system.net configuration section. In this article we will make an application that can be used to load and save mail settings.

 

Using the Code:

To make your application send emails to customers, follow these steps:

1.       Create a new windows application using Visual Studio 2005/2008.

2.       Rename Form1 to MailSettingsForm.

3.       Add a Label to the MailSettingsForm and rename it to FromLabel.

4.       Add another Label to the MailSettingsForm and rename it to HostLabel.

5.       Add another Label to the MailSettingsForm and rename it to UserNameLabel.

6.       Add another Label to the MailSettingsForm and rename it to PasswordLabel.

7.       Add a TextBox to the MailSettingsForm and rename it to FromTextBox.

8.       Add another TextBox to the MailSettingsForm and rename it to HostTextBox.

9.       Add another TextBox to the MailSettingsForm and rename it to PortTextBox.

10.   Add another TextBox to the MailSettingsForm and rename it to UserNameTextBox.

11.   Add another TextBox to the MailSettingsForm and rename it to PasswordTextBox and set the PasswordChar property to *.

12.   Add a CheckBox to the MailSettingsForm and rename it to DefaultCredentialsCheckBox.

13.   Import the System.Reflection, System.Configuration and System.Net.Configuration namespaces using the following statement:

using System.Reflection;

using System.Configuration;

using System.Net.Configuration;

14.   The System.Reflection namespace contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata.

15.   The System.Configuration namespace contains the types that provide the programming model for handling configuration data.

16.   The System.Net.Configuration namespace contains classes that applications use to programmatically access and update configuration settings for the System.Net namespaces.

17.   Add the following code to the MaillsettingsForm Load event to load the mail settings at the form startup:

private Configuration config;

private MailSettingsSectionGroup mailSettings;

private int port;

 

private void MailSettingsForm_Load(object sender, EventArgs e)

{

    try

    {

        config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

        mailSettings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

        FromTextBox.Text = mailSettings.Smtp.From;

        HostTextBox.Text = mailSettings.Smtp.Network.Host;

        PortTextBox.Text = mailSettings.Smtp.Network.Port.ToString();

        UserNameTextBox.Text = mailSettings.Smtp.Network.UserName;

        PasswordTextBox.Text = mailSettings.Smtp.Network.Password;

        DefaultCredentialsCheckBox.Checked = mailSettings.Smtp.Network.DefaultCredentials;

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

                                 i.            First we create an object of the Configuration class and name it config. This object represents a configuration file that is applicable to a particular computer, application, or resource.

                               ii.            We then create an object of the MailSettingsSectionGroup class and name it mailSettings. This class corresponds to the <mailSettings> Element (Network Settings) configuration element, is used to access information about SMTP settings for the local computer and provides programmatic access to information that can be stored in configuration files.

                              iii.            We then create an integer variable named port to hold the port number that we use to connect to the SMTP server.

                             iv.            In the Load event of the MailSettingsForm, we initialize the config object by using the ConfigurationManager class that provides access to configuration files for client applications using the OpenExecConfiguration method and pass to it the location of the assembly that contains the code that is currently executing.

                               v.            We then initialize the mailSettings object by calling Configuration.GetSectionGroup method that is used to obtain a specific ConfigurationSectionGroup from a Configuration object and and passing to it the mailSettings section under the system.net section and casting it to MailSettingsSectionGroup object.

                             vi.            Now we have the mailSettings object loaded with the settings in the configuration file.

                            vii.            We set the FromTextbox text property to the mailSettings.Smtp.From property.

                          viii.            We set the HostTextbox text property to the mailSettings.Smtp.Network.Host property.

                             ix.            We set the PortTextbox text property to the mailSettings.Smtp.Network.Port property.

                               x.            We set the UserNameTextbox text property to the mailSettings.Smtp.Network.UserName property.

                             xi.            We set the PasswordTextbox text property to the mailSettings.Smtp.Network.Password property.

                            xii.            We set the DefaultCredentialsCheckBox Checked property to the mailSettings.Smtp.Network. DefaultCredentials property.

18.   Now you have loaded the mail settings from the configuration file and places them to the MailSettingsForm.

19.   Add an ErrorProvider component to the MailSettingsForm and name it errorProvider. The Error Provider  provides a user interface for indication that a control on the form has an error associated with it.

20.    Add a button to the MailSettingsForm and name it SaveSettingsButton and double click the SaveSettingsButton in the designer to create the Click event handler in the code.

21.   Add the following code to the SaveSettingsButton Click Event Handler:

private void SaveSettingsButton_Click(object sender, EventArgs e)

{

    try

    {

        errorProvider.Clear();

        if (string.IsNullOrEmpty(FromTextBox.Text))

        {

            errorProvider.SetError(FromTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(HostTextBox.Text))

        {

            errorProvider.SetError(HostTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(PortTextBox.Text))

        {

            errorProvider.SetError(PortTextBox, "Required");

            return;

        }

        else

        {

            if (!int.TryParse(PortTextBox.Text, out port))

            {

                errorProvider.SetError(PortTextBox, "Invalid");

                return;

            }

        }

 

        DialogResult result = MessageBox.Show("Are you sure you want to Save?",

            "Are you sure you want to Save?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

 

        if (result == DialogResult.Yes)

        {

            int.TryParse(PortTextBox.Text, out port);

            mailSettings.Smtp.From = FromTextBox.Text;

            mailSettings.Smtp.Network.Host = HostTextBox.Text;

            mailSettings.Smtp.Network.Port = port;

            mailSettings.Smtp.Network.UserName = UserNameTextBox.Text;

            mailSettings.Smtp.Network.Password = PasswordTextBox.Text;

            mailSettings.Smtp.Network.DefaultCredentials = DefaultCredentialsCheckBox.Checked;

 

            config.Save(ConfigurationSaveMode.Modified);

 

            MessageBox.Show("The Operation is successfully completed", "Success",

                MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

                                 i.            First of all we clear any error in the errorProvider component by calling the Clear method of the errorProvider.

                               ii.            We check that the user enters a value in the FromTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

                              iii.            We then check that the user enters a value in the HostTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

                             iv.            We then check that the user enters a value in the PortTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text. If the user types a value in the Port and this value is not an integer number we notify the user that this value is invalid.

                               v.            We then notify the user to confirm saving these settings or not.

                             vi.            If the user wants to save these settings by clicking on yes, then we get the port number and set the mailSettings.Smtp.From to the text in the FromTextBox.

                            vii.            Set the mailSettings.Smtp.Network.Host to the HostTextBox text property.

                          viii.            Set mailSettings.Smtp.Network.Port to the port number in the PortTextBox.

                             ix.            Set mailSettings.Smtp.Network.UserName to the UserNameTextbox text property.

                               x.            Set mailSettings.Smtp.Network.Password to the PasswordTextBox text property.

                             xi.            We then set if these credentials are the default credentials to use when connecting to SMTP server.

                            xii.            We then save the modified sections of the configuration file and tell the user that the save operation is successfully completed.

                          xiii.            If there is any exception, we will display a message box containing the exception message.

22.   Now compile and run the application.

23.   The mail settings will be loaded to you. Type your preferred settings and click on the Save Settings, You will be notified if the mail settings is saved or not.

Note: You can apply the techniques in the How to: Check that a server is reachable across the network using C# and How to: Telnet a remote service using C# to ping the SMTP server and test that the SMTP service is running.

Now you have an application that can load and save mail settings and this is the final look of the application:

(72) Comments

Blog Message adidas superstar uk 6

If you can remember, the Air Jordan 8 only had three original colorways that released in 1993. adidas superstar uk 6 http://lamaisondemalaure.com/lamais.asp?ID=adidas-superstar-uk-6


Blog Message http://www.titi.co.il/discreet-apartments.html

I think this is a real great article. Will read on...


Blog Message http://www.facebook.com/investwpg

Im obliged for the post. Really Great.


Blog Message http://www.cangworld.com/bbs/home.php?mod=space&uid=1185461

I cannot thank you enough for the article post. Awesome.


Blog Message http://www.animalichepassione.it/modules.php?name=Your_Account&op=userinfo&username=HalinaBard

Very good blog post.Much thanks again. Awesome.


Blog Message http://cheshiretales.com/

Great, thanks for sharing this post.Thanks Again. Awesome.


Blog Message http://www.myfreewarefiles.com

Really appreciate you sharing this article post.Much thanks again. Really Great.


Blog Message http://newsblaze.com/issues/personal-finance/3-legitimate-money-making-methods-to-supplement-your-income_73555/

Way cool! Some very valid points! I appreciate you penning this write-up and the rest of the website is extremely good.


Blog Message http://www.restokitch.com/members/chive22crack/activity/74109/

Really enjoyed this article post.Really looking forward to read more. Fantastic.


Blog Message http://mybulletinboard.net63.net/member.php?action=profile&uid=30892

I value the blog post.Thanks Again.


Blog Message http://blog97.com

Since search engines take hundreds and hundreds of factors into


Blog Message http://jimwdahms45.bravesites.com/entries/general/tips-on-how-to-spy-on-someones-snapchat

Thanks for sharing, this is a fantastic article. Awesome.


Blog Message http://www.dhzx168.com/comment/html/index.php?page=1&id=453834290

There as definately a great deal to know about this issue. I love all of the points you made.


Blog Message http://www.unblockedhappywheels.com/planet-minecraft/

Very neat article.Really thank you! Fantastic.


Blog Message http://www.escortfox.it/topvip-escorts/

I value the blog post.Much thanks again.

First Previous 1 2 3 4 5 Next Last 
Rating
Name
Email
Comment