c# - 如何在 .NET 中为 SmtpClient 对象设置用户名和密码?

标签 c# 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");

关于c# - 如何在 .NET 中为 SmtpClient 对象设置用户名和密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766928/

相关文章:

c# - 更改电子邮件中自动附加文件的名称

c# - 无法加载文件或程序集 'xxx.dll' 或其依赖项之一。指定的模块无法找到

c# - 无法使用 GoDaddy 配置的 Office 365 帐户中的 C# 代码发送电子邮件

.net - 'System.Net.Mail.SmtpClient' 类型的“使用”操作数必须实现 'System.IDisposable' - (.NET 3.5)

c# - 我将如何获得以特定前缀开头的所有 MySQL 数据库使用的总磁盘空间?

c# - 如何最好地管理 SMTP 客户端

smtp - 后缀 : check_client_access not working

c# - C# 在 foreach 中重用变量是否有原因?

c# - 并发执行有限数量的任务

c# - C#中有没有懒惰的 `String.Split`