如何在.NET中设置SmtpClient对象的用户名和密码?
我看到不同版本的构造函数,一个使用web.config中的信息,一个指定主机,一个指定主机和端口。 但是,如何将用户名和密码设置为与web.config不同的内容? 我们有问题,我们的内部smtp被一些高安全性的客户端阻止,我们想要使用他们的smtp服务器,有没有办法从代码而不是web.config做到这一点?
在这种情况下,如果没有数据库可用,我将如何使用web.config凭据?
public static void CreateTestMessage1(string server, int port) { string to = "jane@contoso.com"; string from = "ben@contoso.com"; string subject = "Using the new SMTP client."; string body = @"Using this new feature, you can send an e-mail message from an application very easily."; MailMessage message = new MailMessage(from, to, subject, body); SmtpClient client = new SmtpClient(server, port); // Credentials are necessary if the server requires the client // to authenticate before it will send e-mail on the client's behalf. client.Credentials = CredentialCache.DefaultNetworkCredentials; try { client.Send(message); } catch (Exception ex) { Console.WriteLine("Exception caught in CreateTestMessage1(): {0}", ex.ToString()); } }
SmtpClient可以被代码使用:
SmtpClient mailer = new SmtpClient(); mailer.Host = "mail.youroutgoingsmtpserver.com"; mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
使用NetworkCredential
是的,只需将这两行添加到您的代码。
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password"); client.Credentials = credentials;
SmtpClient MyMail = new SmtpClient(); MailMessage MyMsg = new MailMessage(); MyMail.Host = "mail.eraygan.com"; MyMsg.Priority = MailPriority.High; MyMsg.To.Add(new MailAddress(Mail)); MyMsg.Subject = Subject; MyMsg.SubjectEncoding = Encoding.UTF8; MyMsg.IsBodyHtml = true; MyMsg.From = new MailAddress("username", "displayname"); MyMsg.BodyEncoding = Encoding.UTF8; MyMsg.Body = Body; MyMail.UseDefaultCredentials = false; NetworkCredential MyCredentials = new NetworkCredential("username", "password"); MyMail.Credentials = MyCredentials; MyMail.Send(MyMsg);
由于并不是所有的客户端都使用经过身份validation的SMTP帐户,所以只有在web.config文件中提供了应用程序密钥值的情况下,才使用SMTP帐户。
这里是VB代码:
sSMTPUser = ConfigurationManager.AppSettings("SMTPUser") sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword") If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword) sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes End If NetClient.Send(Message)