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:

(128) Comments

Blog Message https://temporaryprotection.co.uk

Sent the first post, but it wasn`t published. I am writing the second. It as me, the African tourist.


Blog Message http://jump.dokoya.com/?url=https://www.twitch.tv/videos/339415606

Really enjoyed this blog.Really looking forward to read more. Want more.


Blog Message http://boyscagar.net46.net//index.php?a=profile&u=ralphsalas4

online social sites, I would like to follow everything new


Blog Message http://outletforbusiness.com/2018/12/12/ciri-khas-dari-agen-bola-online-4/

placing the other person as webpage link on your page at suitable place and other person will also do similar in favor of


Blog Message https://www.datafilehost.com/d/94f2053f

Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is fantastic, as well as the content!. Thanks For Your article about &.


Blog Message http://miles3834xk.rapspot.net/mcelroy-gives-a-helpful-overview-of-the-entire-process-make-a-home-viable

Unfortunately, fanminds did not present at the GSummit, so their slides are not included. I\ ad love to hear more about their projects. Please get in touch! Jeff at gamification dot co


Blog Message http://martinez8630wd.metablogs.net/your-goal-simply-stated-is-to-build-up-enough-assets-to-asset-liability-matching-or-time-segmentation

Major thanks for the blog post.Really looking forward to read more. Really Great.


Blog Message http://www.jzzk.net/bbs/home.php?mod=space&uid=2447756&do=profile

Whoa! This blog looks just like my old one! It as on a totally different topic but it has pretty much the same page layout and design. Outstanding choice of colors!


Blog Message http://articulos.ml/blog/view/672304/regardless-of-how-knowledgeable-you-are-you-may-need-a-few-mca-reviews

Really enjoyed this article.Really thank you! Keep writing.


Blog Message https://justpaste.it/3o5pl

Major thanks for the post.Really looking forward to read more. Really Great.


Blog Message http://www.geogr.msu.ru/bitrix/rk.php?goto=http://scenepurple7.uniterre.com/661077/Interested+In+A+Fast+Mesothelioma+Symptoms%3F+You+Have+to+Observe+This.html

I value the article.Thanks Again. Will read on


Blog Message http://pycho.org/index.php?mid=qna&document_srl=1666156

Wow, fantastic blog layout! How long have you been blogging for?


Blog Message https://www.smore.com/15hxt-ps4-remote-play-pc

There is evidently a bundle to realize about this. I feel you made various nice points in features also.


Blog Message http://www.captnstable.com/how-perform-free-games-with-xbox-game-live/

Only wanna remark that you have a very nice site, I love the design and style it really stands out.


Blog Message http://www.youmacao.com/__media__/js/netsoltrademark.php?d=www.colourlovers.com%2Flover%2Fdominiquegoettle

Very informative article.Much thanks again. Want more.

First Previous 1 2 3 4 5 6 7 8 9 Next Last 
Rating
Name
Email
Comment