我看到了不同版本的构造函数,一种使用来自 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");
关于c# - 如何在 .NET 中为 SmtpClient 对象设置用户名和密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766928/