【发布时间】:2010-09-22 20:07:39
【问题描述】:
我创建了使用 SMTP 发送消息的新 ASP.NET Web 应用程序。问题是 smtp 未从发送消息的人那里进行身份验证。
如何使 SMTP 在我的程序中通过身份验证? C# 是否有一个具有输入用户名和密码属性的类?
【问题讨论】:
标签: c# authentication smtp
我创建了使用 SMTP 发送消息的新 ASP.NET Web 应用程序。问题是 smtp 未从发送消息的人那里进行身份验证。
如何使 SMTP 在我的程序中通过身份验证? C# 是否有一个具有输入用户名和密码属性的类?
【问题讨论】:
标签: c# authentication smtp
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);
}
}
}
你可以使用上面的代码。
【讨论】:
smtpClient.Port(123)
你如何发送消息?
System.Net.Mail 命名空间中的类(这可能是您应该使用的)完全支持身份验证,可以在 Web.config 中指定,也可以使用 SmtpClient.Credentials 属性。
【讨论】:
在发送消息之前设置Credentials 属性。
【讨论】:
确保在调用SmtpClient.UseDefaultCredentials = false之后设置SmtpClient.Credentials。
顺序很重要,因为设置 SmtpClient.UseDefaultCredentials = false 会将 SmtpClient.Credentials 重置为 null。
【讨论】:
要通过 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);
【讨论】:
在我的情况下,即使遵循上述所有内容。我必须将我的项目从 .net 3.5 升级到 .net 4 才能授权我们的内部 Exchange 2010 邮件服务器。
【讨论】: