![](/img/trans.png)
[英]How can I login to ASP.Net Forms Authenticated site using C#?
[英]How can I make SMTP authenticated in C#
我創建使用SMTP發送消息的新ASP.NET Web應用程序。 問題是smtp未被發送郵件的人驗證。
如何在程序中對SMTP進行身份驗證? C#是否具有一個具有用於輸入用戶名和密碼的屬性的類?
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.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);
您如何發送消息?
System.Net.Mail
命名空間中的類(可能是您應該使用的類)完全支持身份驗證,可以在Web.config中指定,也可以使用SmtpClient.Credentials
屬性。
就我而言,即使遵循以上所有條件。 我必須將我的項目從.net 3.5升級到.net 4,以針對我們的內部Exchange 2010郵件服務器進行授權。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.