如何从SMTP服务器发送电子邮件?

时间:2016-07-30 17:16:56

标签: c# asp.net email smtp

您好我有托管的Windows Server 2008 R2 Enterprise和购买的域名。我已经将我的域上的所有内容指向我的服务器的dns并将我的ASP.Net站点上传到IIS。我还设置了一个SMTP功能,所以现在我尝试从我的SMTP发送电子邮件,但我不能,因为应用程序说用户未经过身份验证。 这是我的页面的源代码:

MailMessage activationMail = new MailMessage();
                activationMail.From = new MailAddress("no-reply@mydomain.com", "MyGame");
                activationMail.To.Add(RegistrationEmail.Text);
                StreamReader sRead = new StreamReader(Server.MapPath("~/Mails/ActivationMail.html"));
                string readFile = sRead.ReadToEnd();
                string Strcontent = "";
                Strcontent = readFile;
                Strcontent = Strcontent.Replace("[Name]", RegistrationRealName.Text);
                Strcontent = Strcontent.Replace("[Username]", RegistrationUsername.Text);
                Strcontent = Strcontent.Replace("[Password]", RegistrationPasswordCreate.Text);
                Strcontent = Strcontent.Replace("[useractivation]", useractivation);
                Strcontent = Strcontent.Replace("[Site]", site);
                Strcontent = Strcontent.Replace("[Facebook]", "facebook");
                activationMail.Subject = "My Game - Registration";
                activationMail.Body = Strcontent.ToString();
                sRead.Close();
                activationMail.IsBodyHtml = true;
                activationMail.BodyEncoding = UTF8Encoding.UTF8;
                SmtpClient client = new SmtpClient();
                client.Host = "mydomain"; 
                NetworkCredential cr = new NetworkCredential();
                cr.UserName = "User from AD DS";
                cr.Password = "Password of User";
                client.UseDefaultCredentials = false;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Port = 25;
                client.Timeout = 10000;
                client.Send(activationMail);

注意:我的域名与我的林域不同。我还尝试将我的林域设置为客户端。但是结果却相同。我在Web.config上有这些设置

    <mailSettings>
      <smtp from="no-reply@mydomain">
          <network defaultCredentials="false" host="localhost" />
      </smtp>
  </mailSettings>

我的SMTP服务器的设置如下:

  • IP地址=我的服务器的IP
  • 身份验证= Standar&amp;检查Windows身份验证,检查TSL,将默认域设置为我的域(而不是我的MX记录mail.domain)。不检查匿名身份验证。
  • 连接=只有我的服务器的IP才能访问
  • 中继=只有我购买的域名(不是MX记录)才能访问
  • 出站安全=标准身份验证(来自AD DS的用户 - 与上面我的cs文件中的用户相同的凭据),已启用TLS
  • 高级投放选项=我在那里设置了我的域名(不是MX记录 - 给我一个错误)

有人知道我做错了什么吗?

2 个答案:

答案 0 :(得分:0)

添加以下代码,因为您没有向smtp提供任何凭据:

client.Credentials = cr; 

像:

 NetworkCredential cr = new NetworkCredential();
 cr.UserName = "User from AD DS";
 cr.Password = "Password of User";
 client.Credentials = cr; 
 client.UseDefaultCredentials = false;
 client.DeliveryMethod = SmtpDeliveryMethod.Network;
 client.Port = 25;
 client.Timeout = 10000;
 client.Send(activationMail);

答案 1 :(得分:0)

尝试添加以下两行:

client.EnableSsl = false;
client.Credentials = cr;