How to solve System.Net.Sockets.SocketException on C# Xamarin?

4.8k views Asked by At

In my app I want to send an email, it works fine in debugging mode but when I release it I get this error. I'm already catching the exception but that causes it to not send the email and I really need this function to work. How is this caused and how can it be solved that it also works when deployed? I've tested it on multiple phones and they all gave this exception so the phone used is not the issue.

Corresponding code:

 this.Dismiss();
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Name", "Email"));
message.To.Add(new MailboxAddress("Name", "Email"));
message.Subject = "Test"

message.Body = new TextPart("plain")
{
    Text = @"Test"
};

using (var client = new MailKit.Net.Smtp.SmtpClient())
{
    try
    {
        client.ServerCertificateValidationCallback = (s, c, h, e) => true;
        client.Connect("smtp.gmail.com", 25, false);

        // Note: since we don't have an OAuth2 token, disable
        // the XOAUTH2 authentication mechanism.

        client.AuthenticationMechanisms.Remove("XOAUTH2");
        client.Authenticate("Account", "Password");

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

        Toast.MakeText(this.Activity, "Thanks for the email", Android.Widget.ToastLength.Short).Show();
    }
    catch (System.Net.Sockets.SocketException e)
    {
        Toast.MakeText(this.Activity, "Connection error, please try again later!", Android.Widget.ToastLength.Short).Show();
    }

At "Name" and "Email" is the corresponding information but changed it for this example. Same as "Account" and "Password" in client.Authenticate for security.

EDIT: Error code is 11001, and message was could not resolve host "smtp.gmail.com" , this also happens on the other ports. The thing I find weird is that it works when debugging on my emulator, but not on the phones when it's deployed.

1

There are 1 answers

3
Ewan Klomp On BEST ANSWER

Dumb mistake, I forgot to add permissions to acces internet.

Bit weird though that it does work in debugging mode then.