[c#] .NET에서 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");


답변

사용하다 NetworkCredential

네,이 두 줄을 코드에 추가하십시오.

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

client.Credentials = credentials;


답변

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


답변

모든 클라이언트가 인증 된 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)


답변