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

时间:2010-05-04 16:05:44

标签: 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());
    }              
}

4 个答案:

答案 0 :(得分:273)

SmtpClient可以由代码使用:

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

答案 1 :(得分:25)

使用NetworkCredential

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

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

client.Credentials = credentials;

答案 2 :(得分:5)

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);

答案 3 :(得分:-1)

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