Using System.Net.Mail in ASP NET MVC 6 project

2019-04-20 17:20发布

问题:

I have trouble creating a simple mock mail sender within an ASP NET 5 project.

Here the method :

    public static Task SendMail(string Email, string Subject, string Body)
    {
        SmtpClient client = new SmtpClient();
        client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
        client.PickupDirectoryLocation = "C:\\TMP";

        MailAddress from = new MailAddress("jane@contoso.com", "Jane " + (char)0xD8 + " Clayton", System.Text.Encoding.UTF8);
        MailAddress to = new MailAddress(Email);

        MailMessage message = new MailMessage(from, to);
        message.Body = Body;
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.Subject = Subject;
        message.SubjectEncoding = System.Text.Encoding.UTF8;

        client.Send(message);
        message.Dispose();

        return Task.FromResult(0);
    }

I have included the dependency 'System.Net.Mail', but a tooltip says that the library is available in DNX 4.5.1 but not in DNX Core 5.0, and the project will not compile.

In my project.json there is :

"frameworks": {
    "dnx451": { },
    "dnxcore50": { }
}

回答1:

I don't believe that the SmtpClient is being ported to .Net Core. (You can use the unofficial reverse package lookup to find the new NuGet packages, and there isn't one.)

Since you don't need .Net Core, you can remove the dnxcore50 entry from your frameworks in your project.json.



回答2:

As of today, it is now possible to send email on dnxcore50 in addition to net451 (and lots of other platforms) using MailKit

I'm using rc1 of ASP.NET 5 and I added these dependencies to my project.json to bring in the needed nugets

"MimeKit": "1.3.0-beta1",
"MailKit": "1.3.0-beta1"

So the lack of System.Net.Mail in dnxcore50 is no longer a problem, the MailKit library is actually much more feature rich than any of the old System.Net.Mail stuff.

Huge Thanks to Jeffrey Stedfast for his hard work.



回答3:

For .NET Core be sure to obtain MailKit by updating project.json to add it as a dependency...

"MailKit": "~1.6.0"

See MailKit on GitHub for a complete example: https://github.com/jstedfast/MailKit



回答4:

If you have set up your project in Visual Studio 2017, then this solution will work:

  1. Edit the .csproj file of your project. Right-click on the project name and choose 'Edit Project1.csproj' (in case your project name is Project1). The project's XML file opens. Change the 'TargetFramework' to net452 and add a 'RuntimeIdentifier' tag with value win7-x86. So it looks like this:

    [PropertyGroup] [TargetFramework]net452[/TargetFramework] [RuntimeIdentifier]win7-x86[/RuntimeIdentifier] [/PropertyGroup]

(replace all brackets bij 'less than' and 'greater than' signs) Your project will be linked to the .NET Framework 4.5.2 and all libraries will be available then, including the System.NET.Mail namespace.

For me, this is a working solution...:-)