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

2024-02-16

我看到不同版本的构造函数,一种使用 web.config 中的信息,一种指定主机,一种指定主机和端口。但是如何将用户名和密码设置为与 web.config 不同的内容呢?我们遇到的问题是我们的内部 smtp 被一些高安全性客户端阻止,并且我们想使用他们的 smtp 服务器,有没有办法从代码而不是 web.config 来做到这一点?

例如,在这种情况下,如果数据库中没有可用的 web.config 凭据,我将如何使用 web.config 凭据?

public static void CreateTestMessage1(string server, int port)
{
    string to = "[email protected] /cdn-cgi/l/email-protection";
    string from = "[email protected] /cdn-cgi/l/email-protection";
    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");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在.NET中为SmtpClient对象设置用户名和密码? 的相关文章

随机推荐