nam
nam

Reputation: 23749

SocketException: No such host is known

In my ASP.NET Core 1.1.1 app developed on VS2017 Ver 15.3.3, I'm using Account confirmation and password recovery in ASP.NET Core and MailKit to implement the above article's functionality but I'm getting the following error:

Note:

  1. The error occurs at line await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false); of SendEmailAsync(...) method below and
  2. at line await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); of the Register(...) post method also shown below:

ERROR

SocketException: No such host is known

MessageServices.cs class

public class AuthMessageSender : IEmailSender, ISmsSender
{
    public async Task SendEmailAsync(string email, string subject, string message)
    {
        // Plug in your email service here to send an email.
        //return Task.FromResult(0);
        var emailMessage = new MimeMessage();

        //You can if required (and I have done in my code) set the LocalDomain used when communicating with the SMTP server
        //This will be presented as the origin of the emails. In my case I needed to supply the domain so that our internal testing SMTP server would accept and relay my emails.
        //We then asynchronously connect to the SMTP server. The ConnectAsync method can take just the uri of the SMTP server or as I’ve done here be overloaded with a port and SSL option. For my case when testing with our local test SMTP server no SSL was required so I specified this explicitly to make it work.
        emailMessage.From.Add(new MailboxAddress("MyName", "[email protected]"));
        emailMessage.To.Add(new MailboxAddress("", email));
        emailMessage.Subject = subject;
        emailMessage.Body = new TextPart("plain") { Text = message };

        using (var client = new SmtpClient())
        {
            client.LocalDomain = "smtp.MyDomain.com";
            await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);
            await client.SendAsync(emailMessage).ConfigureAwait(false);
            await client.DisconnectAsync(true).ConfigureAwait(false);
        }
    }

Register post method in AccountController.cs

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

UPDATE

Not certain, but the error may be related to me not using my email host info correctly:

  1. I'm using a website/email hosting company DiscountASP.NET's webmail feature. Their SMTP Server name for each subscriber is smtp.YourDomainName.com. And hence, in the SendEmailAsync(...) method above, I'm using client.LocalDomain = "smtp.MyDomain.com";
  2. For MailKit implementation I'm following Sending email via a SMTP server section of this article.

Upvotes: 2

Views: 6787

Answers (1)

Ahmed Khaled
Ahmed Khaled

Reputation: 13

Open your cmd and write ipconfig /all for windows and search for your hostname of your PC hostname in console then enter your Hostname in this function

using (var client = new SmtpClient())
    {
        client.LocalDomain = "smtp.MyDomain.com";
        await client.ConnectAsync("YourHostName", 25,false);
        await client.SendAsync(emailMessage).ConfigureAwait(false);
        await client.DisconnectAsync(true).ConfigureAwait(false);
    }

Upvotes: 0

Related Questions