简体   繁体   中英

Store email credential in web.config file

I am trying to store email credential from Startup.cs file to web.config file.

var value = ConfigurationManager.AppSettings["appSettings"];
SmtpClient mySmtpClient = new SmtpClient("smtp.gmail.com");

mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("service@gmail.com", "123456");
mySmtpClient.Credentials = basicAuthenticationInfo;
mySmtpClient.EnableSsl = true;
mySmtpClient.Port = 587;

MailAddress from = new MailAddress("service@gmail.com", "ActiveDirectoryInformation");
MailAddress to = new MailAddress("test@gmail.com");
//MailAddress to = new MailAddress("it@sarajevoosiguranje.ba");
System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage(from, to);

myMail.Subject = "ActiveDirectory";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;

// set body-message and encoding
myMail.Body = @"Ukupno novih korisnika:" + noviKorisnika + "<br>" +
              @"Ukupno izmjenjenih korisnika: " + izmjenjenihKorisnika;
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;

And I create in my app.config file

<appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="smtpServer" value="smtp.net" />
    <add key="Username" value="service@gmail.com"/>
    <add key="Password" value="test123456abc"/>
    <add key="EnableSsl" value = "true"/>
    <add key="smtpPort" value="587" />
    <add key="from" value="service@gmail.com" />
    <add key="to" value ="test@gmail.com"></add>    
</appSettings>

The reason why I do that is that I want to publish this application live, and maybe in future when I change sender or receiver email address I don't want to compile application again and publish it.

It is easy way to store everything in app.config and read from there.

Any suggestion how to do this?

I'm not sure if this will work for you or not but I was able to store SMTP information inside the app.config file for one of my old C# applications.

However, the To: address was not stored as part of the credentials so I stored those information in a local SQLite file.

To retrieve the settings you just need to initialize a SmtpClient object which will read from the local config file.

Hope this helps.

        public static void WriteDefaultSMTPSettingsToConfigurationFile()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

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

            SmtpSection smtpSection = mailSettingsSectionGroup.Smtp;

            if (!smtpSection.ElementInformation.IsPresent)
            {
                smtpSection.DeliveryFormat = SmtpDeliveryFormat.International;
                smtpSection.DeliveryMethod = SmtpDeliveryMethod.Network;

                SmtpNetworkElement smtpNetworkElement = smtpSection.Network;
                smtpNetworkElement.Host = "localhost";
                smtpNetworkElement.Port = 465;
                smtpNetworkElement.EnableSsl = true;
                smtpNetworkElement.UserName = "username";
                smtpNetworkElement.Password = "password";

                config.Save();
                ConfigurationManager.RefreshSection("system.net/mailSettings");
            }
        }

As I have understood, you want to store information in App.config file which is pretty easy.

Step 1

Add System.Configuration.dll reference to your project if you don't have it already.

Project > myAwsomeProject > References > Add Reference > Find System.Configuration.dll

(or something like that) and add it to your project.

Step 2

import the System.Configuration.dll using:

using System.Configuration;

Then create a function or write the code in the third step under your main();

Step 3

Create an instance of the Configuration class that refers to your App.config file

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

Step 4

Use the following syntax to read from your App.config file

config.AppSettings.Settings["mykey"].Value

in which you would replace the "mykey" value with the corresponding key name. For example in your case Username or Password

Step 5

Use the following syntax to write to/change value of a key

config.AppSettings.Settings["mykey"].Value = "value";

"mykey" is the key and "value" is the desired value

Do NOT forget to save the configuration file after you write to it or after all the operations are done!!!

config.Save();

Step 6 (Optional)

You can also add and remove keys to your App.Config file

config.AppSettings.Settings.Add("newKey", "value");         
config.AppSettings.Settings.Remove("mykey");

Again after each operation concerning the modification of the file. Save the file

config.Save();

Important Note

The app.config file is not the one you see in your solution explorer in visual studio. The one in the solution explorer will not be modified even after it is saved.

The app.config that you will be using and modifying will be located in C:\Users\yourUsername\source\repos\yourAwsomeProject\yourAwsomeProject\bin\Debug

or if it is in release mode C:\Users\yourUsername\source\repos\yourAwsomeProject\yourAwsomeProject\bin\Release

or if you are using a custom project path

\Path\To\your\Awsome\Project\yourAwsomeProject\bin\Release

and the file will be named as

yourAwsomeProject.exe.config

(Correct me if I am wrong or misunderstood the question)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM