For things like credentials (usernames and passwords) it's generally best to treat them as environmental configuration details. That is, for any given instance of the application operating in any given environment, it would need a handful of configurable values to interact with the mail server:
- Hostname
- Username
- Password
Environmental configuration generally goes in the App.config
or Web.config
file. At its simplest, you might have something like this in the config file:
<appSettings>
<add key="SMTPUsername" value="uname@domain.com" />
<add key="SMTPPassword" value="password" />
</appSettings>
Then to pull them from the configuration in your code, you'd do something like this:
SmtpServer.Credentials = new System.Net.NetworkCredential(
System.Configuration.ConfigurationManager.AppSettings["SMTPUsername"],
System.Configuration.ConfigurationManager.AppSettings["SMTPPassword"]);
You can abstract those settings behind a custom configuration class, have in-code defaults in case of empty values in the configuration, do all sorts of error checking on the configuration values, etc. But ultimately you're pulling the values from the config file.
The config file can then be kept separate from your publicly-visible source code. You'd want a config file included in the source code which contains sample configuration data, so people consuming the project can now how to configure it. But you can keep a not-checked-in local configuration for your own needs, and deploy a custom configuration file to any production server which runs this application. (That's really what configuration files are for, storing values which differ between instances of the same application.)
Whether you create a static
helper method to handle this isn't really relevant to hiding these values. You certainly can create such a method. It doesn't need to be static, if you'd prefer a mailer object which you'd instantiate. (Maybe something which implements IDisposable
and uses that to internally dispose of SMTP object resources? Get as creative as you want, really.) But that abstraction alone doesn't hide your values, it just moves them from one class in the source code to another. You want to remove them from the source code entirely.