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

发布于 2024-08-31 15:02:19 字数 1342 浏览 2 评论 0原文

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

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

public static void CreateTestMessage1(string server, int port)
{
    string to = "[email protected]";
    string from = "[email protected]";
    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());
    }              
}

I see different versions of the constructor, one uses info from web.config, one specifies the host, and one the host and port. But how do I set the username and password to something different from the web.config? We have the issue where our internal smtp is blocked by some high security clients and we want to use their smtp server, is there a way to do this from the code instead of web.config?

In this case how would I use the web.config credentials if none is available from the database, for example?

public static void CreateTestMessage1(string server, int port)
{
    string to = "[email protected]";
    string from = "[email protected]";
    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());
    }              
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

爺獨霸怡葒院 2024-09-07 15:02:19

SmtpClient 可以通过代码使用:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
猫烠⑼条掵仅有一顆心 2024-09-07 15:02:19

使用 NetworkCredential

是的,只需将这两行添加到您的代码中即可。

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;

Use NetworkCredential

Yep, just add these two lines to your code.

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;
不甘平庸 2024-09-07 15:02:19
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);
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);
吻风 2024-09-07 15:02:19

有几件事在其他答案中没有提到。

首先,可能需要直接使用 CredentialCache 而不是 NetworkCredential,以便指定不同的身份验证方案。

在文档中,SMTP 身份验证类型名称列出如下:

“NTLM”、“摘要”、“Kerberos”和“协商”

但是,我必须在 .NET 代码中设置断点才能看到为“AUTH LOGIN”传递的值实际上是“login”。无论如何,这似乎会自动发生,因此只有使用不同的方案才需要这样做。

其次,虽然这里没有人,但您可能不想在 NetworkCredential 中指定域名。这样做会导致 SmtpClient 传递 example.com\username 形式的用户名,这几乎肯定不会被邮件服务器接受。 (如果您的邮件服务器对其身份验证要求不严格,您可能不知道自己无法进行身份验证。)

var nc = new NetworkCredential(
   username,
   password
   // no domain!
);

// only if you need to specify a particular authentication scheme,
// though it doesn't hurt to do this anyway if you use the right scheme name
var cache = new CredentialCache();
cache.Add(smtpServerName, port, "NTLM", nc);
// can add more credentials for different combinations of server, port, and scheme

smtpClient.Credentials = cache;

最后,请注意,如果您还设置了 UseDefaultCredentials,则无需设置 UseDefaultCredentials >凭证,因为它们都基于相同的基础值。设置两者可能会导致问题,因为它们只会相互覆盖。

如果有疑问,请使用 WireShark 并暂时禁用 SSL(以查看网络帧,否则它们会被加密),并确认您的 SMTP 身份验证正常工作。 (在 WireShark 中使用“smtp”过滤器)。

There are a couple of things not mentioned in other answers.

First, it can be necessary to use CredentialCache instead of NetworkCredential directly, in order to specify different authentication schemes.

In the documentation, the SMTP authentication type names are listed as:

"NTLM", "Digest", "Kerberos", and "Negotiate"

However I had to breakpoint within the .NET code to see that the value being passed for "AUTH LOGIN" was actually "login". This seems to happen automatically anyway, so this is only necessary to use different schemes.

Second, though no one here is, you probably do NOT want to specify a domain name in your NetworkCredential. Doing so results in SmtpClient passing a username of the form example.com\username which is almost guaranteed to not be accepted by a mail server. (And if your mail server is loose with its authentication requirements, you may not know that you are failing to authenticate.)

var nc = new NetworkCredential(
   username,
   password
   // no domain!
);

// only if you need to specify a particular authentication scheme,
// though it doesn't hurt to do this anyway if you use the right scheme name
var cache = new CredentialCache();
cache.Add(smtpServerName, port, "NTLM", nc);
// can add more credentials for different combinations of server, port, and scheme

smtpClient.Credentials = cache;

Lastly, note that you do not need to set UseDefaultCredentials if you are also setting Credentials as they are both based on the same underlying value. Setting both can lead to issues since they will just overwrite each other.

If in doubt, use WireShark and disable SSL temporarily (to see the network frames or else they are encrypted), and confirm that your SMTP authentication is working. (Use an "smtp" filter in WireShark).

青芜 2024-09-07 15:02:19

由于并非所有客户都使用经过身份验证的 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)

Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.

Here is the VB code:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文