我创建了使用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 = "your message body
"; message.To.Add("to@anydomain.com"); try { smtpClient.Send(message); } catch(Exception ex) { //Error, could not send the message Response.Write(ex.Message); } } }
您可以使用上面的代码.
确保SmtpClient.Credentials
在通话后设置SmtpClient.UseDefaultCredentials = false
.
顺序很重要,因为设置SmtpClient.UseDefaultCredentials = false
将重置SmtpClient.Credentials
为null.
在发送消息之前设置Credentials属性.