Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sending email example not working with dnxcore50 #293

Closed
mogarick opened this issue Jan 30, 2016 · 12 comments
Closed

Sending email example not working with dnxcore50 #293

mogarick opened this issue Jan 30, 2016 · 12 comments

Comments

@mogarick
Copy link

Hi,

I'm trying to run the sending email example from MacOSX.
The build works without error but when trying to run I get the next error:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

File name: 'System.Net.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ---> System.IO.FileNotFoundException: Could not load the specified file.
File name: 'System.Net.Security'
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName)
   at System.Runtime.Loader.AssemblyLoadContext.Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
   at MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken)
   at MailKit.MailService.Connect(String host, Int32 port, Boolean useSsl, CancellationToken cancellationToken)
   at app01console.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
   at Microsoft.Dnx.ApplicationHost.Program.<>c__DisplayClass3_0.<ExecuteMain>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
System.IO.FileNotFoundException: Could not load the specified file.
File name: 'System.Net.Security'
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName)
   at System.Runtime.Loader.AssemblyLoadContext.Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)

I tried adding System.Net.Security to my dependencies but the error remained.

Could you help me with this? Is this a real bug or Am I missing something?

@joeaudette
Copy link

Since it works on Windows my best guess is there are still bugs I the core fx for other platforms. Not likely a bug in Mailkit/Mimekit so probably best to try again after rc2.

@mogarick
Copy link
Author

Ups!
So It means I'm screwed at this point. I'm working in a prototype and need it for the weekend 😢
I'm really surprised that emailing is not yet working in .net core. It'd be almost as basic as File IO!!!!

@jstedfast
Copy link
Owner

That's odd, the MailKit nuget depends on System.Net.Security v4.0.0-beta-23516, so it should just pull in the required nuget.

@joeaudette
Copy link

Do you have all the same references as what I have in my project.json? https://github.com/joeaudette/cloudscribe/blob/master/src/cloudscribe.Messaging.Email/project.json

If you post your project.json it might help with diagnosis

@jstedfast
Copy link
Owner

Oh, I missed that you are trying this on MacOS X...

It may be a good idea to prototype your app using .NET 4.5 or something that Mono supports and move to .NETCore once it stabilizes. I'm not sure what the state of .NETCore on Mac OS X is.

@jstedfast
Copy link
Owner

Another possibility is that you might need to run dnu restore so that the dependencies are fetched properly?

@mogarick
Copy link
Author

Hi @joeaudette
this is my project.jsonfile:

{
  "version": "1.0.0-*",
  "description": "app01console Console Application",
  "authors": [ "" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",

  "compilationOptions": {
    "emitEntryPoint": true
  },

  "tooling": {
    "defaultNamespace": "app01console"
  },

  "dependencies": {
  },

  "commands": {
    "app01console": "app01console"
  },

  "frameworks": {

    "dnxcore50": {
      "dependencies": {
        "Microsoft.CSharp": "4.0.1-beta-23516",
        "System.Collections": "4.0.11-beta-23516",
        "System.Console": "4.0.0-beta-23516",
        "System.Linq": "4.0.1-beta-23516",
        "System.Threading": "4.0.11-beta-23516",

        "MimeKit": "1.3.0-beta6",
    "MailKit": "1.3.0-beta6" 

      }
    }
  }
}

and this is my program, the same example @jstedfast has in the readme:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace app01console
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey Tribbiani", "[email protected]"));
            message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "[email protected]"));
            message.Subject = "How you doin'?";

            message.Body = new TextPart ("plain") {
                Text = @"Hey Chandler,

I just wanted to let you know that Monica and I were going to go play some paintball, you in?

-- Joey"
            };

            using (var client = new SmtpClient ()) {
                client.Connect ("smtp.friends.com", 587, false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove ("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate ("joey", "password");

                client.Send (message);
                client.Disconnect (true);
            }
        }

    }
}

@mogarick
Copy link
Author

I refactored the example to make it appear more like your code @joeaudette and now I'm getting a warning about the async thing (I haven't had the time to understand how async and non blocking works in c#) when compiling and not getting the System.Net.Security error on execution but the mail is not sent and the program finishes.
Here's the refactored code. Please note that in my local version I used my own email addresses, the smtp server is sendgrid and my credentials are the ones for sendgrid, as that's how they say the thing works.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace app01console
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var mailSender = new EMailSender();
            mailSender.SendEmailAsync();
        }

    }    

    public class EMailSender
    {

        public async Task SendEmailAsync() {

            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey Tribbiani", "[email protected]"));
            message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "[email protected]"));
            message.Subject = "How you doin'?";

            message.Body = new TextPart ("plain") {
                Text = @"Hey Chandler,

I just wanted to let you know that Monica and I were going to go play some paintball, you in?

-- Joey"
            };

            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync("smtp.friends.com", 587, false);
                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                // if(smtpOptions.RequiresAuthentication)
                // {

                // }

                await client.AuthenticateAsync("joey", "password");

                client.Send(message);
                Console.WriteLine("Mensaje enviado");

                client.Disconnect(true);
                Console.WriteLine("Cliente desconectado");

            }

        }
    }

}

@jstedfast
Copy link
Owner

Change your Main() method to be async and await the call to SendEmailAsync():

public static async void Main(string[] args)
{
    var mailSender = new EMailSender();
    await mailSender.SendEmailAsync();
}

The await is important so that the program doesn't exit before the email is sent in a background thread.

What happens is that SendEmailAsync() is spawning a brackground thread to send the email, but since the Main() method is not waiting for it to finish, it exits and the background thread is killed.

Hope that helps.

@mogarick
Copy link
Author

@jstedfast that way I can't compile it 'cause async cannot be used on Main. O found another ways of handling and now the old System.Net.Security exception came to life again but now using async code. Here's the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace app01console
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var mailSender = new EMailSender();
            var task = mailSender.SendEmailAsync();
            Task.WaitAll(task);
        }

    }    

    public class EMailSender
    {

        public async Task SendEmailAsync() {

            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey Tribbiani", "[email protected]"));
            message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "[email protected]"));
            message.Subject = "How you doin'?";

            message.Body = new TextPart ("plain") {
                Text = @"Hey Chandler,

I just wanted to let you know that Monica and I were going to go play some paintball, you in?

-- Joey"
            };

            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync("smtp.sendgrid.net", 587, false);
                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                // if(smtpOptions.RequiresAuthentication)
                // {

                // }

                await client.AuthenticateAsync("myusername", "mypassword");

                client.Send(message);
                Console.WriteLine("Mensaje enviado");

                client.Disconnect(true);
                Console.WriteLine("Cliente desconectado");

            }

        }
    }

}

Here is the exception:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

File name: 'System.Net.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ---> System.IO.FileNotFoundException: Could not load the specified file.
File name: 'System.Net.Security'
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName)
   at System.Runtime.Loader.AssemblyLoadContext.Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
   at MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken)
   at MailKit.MailService.<>c__DisplayClass40_0.<ConnectAsync>b__0()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at app01console.EMailSender.<SendEmailAsync>d__0.MoveNext()
System.IO.FileNotFoundException: Could not load the specified file.
File name: 'System.Net.Security'
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName)
   at System.Runtime.Loader.AssemblyLoadContext.Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)

@jstedfast
Copy link
Owner

If that simple change brought back the System.Net.Security exception, then something is broken with your DNX setup and not with your code or with MimeKit/MailKit for sure.

You may need to go to https://gitter.im/dotnet/coreclr and ask for help, maybe they will have a better idea how to solve this. Unfortunately this is beyond my level of knowledge :(

@mogarick
Copy link
Author

Hi @jstedfast
Could it be possible to leave this issue open just changing the title to something like "Sending email example not working with dnxcore50 in non windows environments" ?
This way any one that is working in a non windows environment can be able to know there is a problem.
If the problem is related to coreclr then a link to the specific issue can be added here for tracking the corresponding issue. What you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants