americanslon americanslon -4 years ago 149
C# Question

ASP 5, MVC 6 sending email

I am dabbling with ASP 5/MVC 6 combination and I find that I no longer know how to do the simplest things. For example how do you send an email?

In MVC 5 world I would do something like this:

using (var smtp = new SmtpClient("localhost"))
{
var mail = new MailMessage
{
Subject = subject,
From = new MailAddress(fromEmail),
Body = message
};

mail.To.Add(toEmail);
await smtp.SendMailAsync(mail);
}


Now this code no longer compiles as
System.Net.Mail
seems to no longer exist. After some poking around the internet it seems it's no longer include in the new core (
dnxcore50
). Which brings me to my question...

How do you send an email in the new world?

And a larger question of where do you find substitutes for all the things that are no longer include in core .Net?

Answer Source

.NET Core has several missing API's at the moment. These include System.Net.Mail.SmtpClient as you have found and also System.ServiceModel.SyndicationFeed too which can be used to build RSS or Atom feeds. The workaround for this is to target the full .NET Framework, instead of .NET Core. You can always target .NET Core once these API's become available.

So in your project.json file you need to remove the reference to dnxcore50 and to add dnx451 for .NET 4.5.1 or dnx46 for .NET 4.6 if it is not already there:

"frameworks": {
  "dnx451": {
    "frameworkAssemblies": {
      "System.ServiceModel": "4.0.0.0"
      // ..Add other .NET Framework references.
    }
  },
  // Remove this to stop targeting .NET Core.
  // Note that you can't comment it out because project.json does not allow comments.
  "dnxcore50": {            
    "dependencies": {
    }
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download