如何在.NET SmtpClient对象中设置的用户名和密码? [英] How to set username and password for SmtpClient object in .NET?

查看:214
本文介绍了如何在.NET SmtpClient对象中设置的用户名和密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到不同版本的构造,人使用信息从web.config中,需要指定主机,一个主机和端口。但我怎么设置的东西从web.config不同的用户名和密码?我们有我们的内部SMTP是一些高安全性的客户端受阻的问题,我们希望用自己的SMTP服务器,有没有办法从code,而不是web.config中做到这一点?

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

 公共静态无效CreateTestMessage1(字符串服务器,诠释端口)
{
    字符串=jane@contoso.com;
    从=ben@contoso.com串;
    字符串主题=使用新的SMTP客户端。
    绳体= @使用这项新功能,你可以很轻松地发送从应用程序的电子邮件。
    消息MAILMESSAGE新= MAILMESSAGE(从,到,主题,正文);
    SmtpClient客户端=新的SmtpClient(服务器,端口);
    如果服务器要求客户端证书//是必要的
    //验证前,将发送电子邮件代表客户。
    client.Credentials = CredentialCache.DefaultNetworkCredentials;    尝试{
        client.Send(消息);
    }
    赶上(例外前){
        Console.WriteLine(异常陷入CreateTestMessage1(){0},
                    ex.ToString());
    }
}


解决方案

该SmtpClient可以用code使用的:

  SmtpClient邮件=新SmtpClient();
mailer.Host =mail.youroutgoingsmtpserver.com;
mailer.Credentials =新System.Net.NetworkCredential(您的用户名,你的密码);

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 = "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());
    }              
}

解决方案

The SmtpClient can be used by code:

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

这篇关于如何在.NET SmtpClient对象中设置的用户名和密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆