我看到了不同版本的构造函数,一个使用来自 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");