Sending mail with ASP.Net vNext

2020-08-11 04:01发布

问题:

In legacy ASP.Net and .Net in general, sending mail was accomplished via System.Net.Mail classes which resided in System.dll. Now with KRE, vNext doesn't seem to have System.Net.Mail as a separate package.

Referencing the "net453" framework in project.json

"frameworks": {
    "aspnet50": { },
    "aspnetcore50": { },
    "net453": {}       // <<< throws compilation errors
},

causes all hell to break loose with errors like:

.NET Framework 4.5.3 error CS0234: The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)

It virtually complains about all vNext dependencies that are part of kpm packages.

So, has anyone figured out a way to send mails using ASP.Net vNext yet?

Note

Even though System appears under References and even though Intellisense shows System.Net.Mail is available for use, the code doesn't compile. E.g., a simple statement like this, although appears valid,

using System.Net.Mail; 

var m = new MailMessage();

will throw compilation error such as:

ASP.NET Core 5.0 error CS0234: The type or namespace name 'Net' does not exist in the namespace 'System' (are you missing an assembly reference?)

ASP.NET Core 5.0 error CS0246: The type or namespace name 'MailMessage' could not be found (are you missing a using directive or an assembly reference?)

Update

With latest Visual Studio 2015 CTP 5, they seemed to have fixed the intellisense glitch. Now System.Net doesn't have Mail namespace anymore. On a side note, the vNext project I created with VS 2015 preview is no longer working - I get an 403.3 error on the home page! Ah, the joy of working with beta software!

回答1:

To use System.Net.Mail your app can target only aspnet50. The aspnetcore50 target has no such support (at least, not right now, as far as I know).

You shouldn't ever have your app target net453 (which, as Luca mentioned in a comment, has since been renamed anyway) because ASP.NET 5 apps don't run on that platform.

An app that targets aspnet50 can generally reference any .NET 4.0+ NuGet package or GAC reference.

So, in your case, remove the net453 and aspnetcore50 targets, and within the aspnet50 target add a framework reference to System.Net.Mail.

A complete alternative would be to find some other existing NuGet package that has support for sending email in both aspnet50 and aspnetcore50, but I doubt such a package exists at this time (though it no doubt will at some point in the future).



回答2:

To follow up... .NET team has stated that porting System.Net.Mail will be less than straightforward and will likely take a while. That's a bummer since a production website usually does more than a little email sending.

In the meantime, someone just released a Core-Clr compatible email API called MailKit. You can read about it here https://github.com/jstedfast/MailKit/issues/212