如何在 C # 中使 SMTP 通过身份验证

我创建了使用 SMTP 发送消息的新 ASP.NET Web 应用程序。问题是没有从发送消息的用户身份验证 smtp。

如何在程序中验证 SMTP?C # 是否有一个具有输入用户名和密码属性的类?

170750 次浏览
using System.Net;
using System.Net.Mail;


using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("from@yourdomain.com");


smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;


message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("to@anydomain.com");


try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}

你可以使用以上代码。

你是怎么传达这个信息的?

System.Net.Mail名称空间中的类(可能是您应该使用的类)完全支持身份验证,可以在 Web.config 中指定,也可以使用 SmtpClient.Credentials属性。

在发送消息之前设置 证件属性。

确保将 SmtpClient.Credentials设置为 之后调用 SmtpClient.UseDefaultCredentials = false

顺序很重要,因为设置 SmtpClient.UseDefaultCredentials = false会将 SmtpClient.Credentials重置为空。

要通过 TLS/SSL 发送消息,需要将 SmtpClient 类的 SSL 设置为 true。

string to = "jane@contoso.com";
string from = "ben@contoso.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Send(message);

在我的情况下,即使遵循以上所有。我不得不把我的项目从。净值3.5至。Net 4授权我们的内部交换2010邮件服务器。