How do I configure email settings in ASP.NET 5?
Try this as a way to keep secret secrets. First, install SecretManager
and configure it with your secrets. When you are on your local machine, you will want to use the values ββfrom SecretManager
. With your hosting (like Azure), you will be using environment variables.
Local: install and configure SecretManager
dnu commands install Microsoft.Extensions.SecretManager
user-secret set "smtp-host" "smtp-mail.outlook.com"
user-secret set "smtp-port" "587"
user-secret set "smtp-username" "myUsername"
user-secret set "smtp-password" "@#$HFS%#$%SFsd"
There's a bug that causes this to happen if you have VS 2015 RC installed. There's a workaround.
Live: using environment variables
Here's an example in an MS Azure web app, although other web hosts probably have similar options.
project.json
Please note that we are targeting only dnx451
. Moreover, we have userSecretsId
.
{
"webroot": "wwwroot",
"version": "1.0.0-*",
"userSecretsId" : "Add-an-arbitrary-user-secrets-id",
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta4",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",
"Microsoft.Framework.ConfigurationModel.UserSecrets": "1.0.0-beta4"
},
"commands": {
"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
},
"frameworks": {
"dnx451": { }
}
/* other configuration omitted */
}
Startup.cs
Now you can access these user secrets locally and when environment variables will overwrite them when available. I just tested this minimal project. He works.
using System;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.ConfigurationModel;
namespace WebApplication1
{
public class Startup
{
public Startup()
{
var configuration = new Configuration();
// the order cascades
// e.g. Environmental variables will overwrite the UserSecrets
configuration.AddUserSecrets();
configuration.AddEnvironmentVariables();
this.Configuration = configuration;
}
IConfiguration Configuration { get; set; }
public void Configure(IApplicationBuilder app)
{
var host = this.Configuration.Get("smtp-host");
var port = this.Configuration.Get("smtp-port");
var username = this.Configuration.Get("smtp-username");
var password = this.Configuration.Get("smtp-password");
var from = "me@domain.com";
var to = "you@domain.com";
var subject = "Dinner on Tues?";
var body = "How about it?";
var mailMessage = new MailMessage(from, to, subject, body);
var smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = false;
smtpClient.Host = host;
smtpClient.Port = Int32.Parse(port);
smtpClient.Credentials = new NetworkCredential(username, password);
smtpClient.EnableSsl = true;
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello SMTP!");
smtpClient.Send(mailMessage);
});
}
}
}
See also:
source to share