MailKit无法解析主机名

问题描述

我有这种方法来测试MailKit Send()函数,但是调用Connect()方法时出现错误。 “无法解析主机名”。我添加一个简单的System.Net.Mail Send()调用,并且使用相同的主机名可以正常运行。但是,MailKit失败。我尝试了用IP地址替换主机名的解决方案,但在该路由下出现证书错误。关于如何解决此问题的任何想法?

[somedomain]是虚构的,真实域已被替换

<mailSettings>
  <smtp deliveryMethod="Network" from="nor[email protected]">
    <network host="mailrelay.somedomain.com" userName="" password="" port="25" />
  </smtp>
</mailSettings>


    private static void SendMail()
    {
        Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var mailSettings = (MailSettingsSectionGroup) oConfig.GetSectionGroup("system.net/mailSettings");

        if (mailSettings == null)
        {
            throw new NullReferenceException($"object mailSettings cannot be null");
        }

        using (var msClient = new System.Net.Mail.SmtpClient())
        {
            msClient.Send("[email protected]","[email protected]","Important Test","Test Email Process");
        }

        //return;

        using (var client = new SmtpClient())
        {
            var message = EmailGenerator.CreateSimpleMessage();
            client.Connect(mailSettings.Smtp.Network.Host,mailSettings.Smtp.Network.Port);
            client.Send(message);
            client.disconnect(true);
        }
    }

解决方法

我发现您要么需要将https://与主机名一起存储在Web config部分,要么在代码中对其进行修改。 System.Net.Mail不在乎,但是我能够使用Uri.TryCreate()复制错误。

Uri.TryCreate($"https://{mailSettings.Smtp.Network.Host}",UriKind.RelativeOrAbsolute,out Uri uri);