2008-11-18 2 views
61

SMTP를 사용하여 메시지를 보내는 새 ASP.NET 웹 응용 프로그램을 만듭니다. 문제는 smtp가 메시지를 보낸 사람으로부터 인증되지 않았기 때문입니다.C에서 SMTP를 인증하려면 어떻게해야합니까?

내 프로그램에서 SMTP를 인증하려면 어떻게합니까? C#에는 사용자 이름과 암호를 입력 할 수있는 특성이있는 클래스가 있습니까?

답변

125
using System.Net; 
using System.Net.Mail; 


SmtpClient smtpClient = new SmtpClient(); 
NetworkCredential basicCredential = 
    new NetworkCredential("username", "password"); 
MailMessage message = new MailMessage(); 
MailAddress fromAddress = new MailAddress("[email protected]"); 

smtpClient.Host = "mail.mydomain.com"; 
smtpClient.UseDefaultCredentials = false; 
smtpClient.Credentials = basicCredential; 

message.From = fromAddress; 
message.Subject = "your subject"; 
//Set IsBodyHtml to true means you can send HTML email. 
message.IsBodyHtml = true; 
message.Body = "<h1>your message body</h1>"; 
message.To.Add("[email protected]"); 

try 
{ 
    smtpClient.Send(message); 
} 
catch(Exception ex) 
{ 
    //Error, could not send the message 
    Response.Write(ex.Message); 
} 

위 코드를 사용할 수 있습니다.

+0

여기서 사용자 이름과 비밀번호는 무엇입니까? mail.mydomain.com은 무엇입니까? 그가 DNS 이름인가요? – Shyju

+5

귀하의 이메일 주소와 비밀번호입니다. mail.mydomain.com은 귀하의 SMTP 서버입니다 (예 : smtp.gmail.com). – Arief

+0

당신은 MailMessage 객체를 using 문으로 감싸 주어야한다. – Ben

1

어떻게 메시지를 보냅니 까?

System.Net.Mail 네임 스페이스의 클래스는 Web.config에 지정되거나 SmtpClient.Credentials 속성을 사용하여 인증을 완벽하게 지원합니다.

6

메시지를 보내기 전에 Credentials 속성을 설정하십시오.

63

(SmtpClient.UseDefaultCredentials = false) 이후 SmtpClient.Credentials으로 설정했는지 확인하십시오.

SmtpClient.UseDefaultCredentials = false 설정이 중요하므로이 순서는 중요합니다. SmtpClient.Credentials을 null로 재설정합니다.

+8

내가 이것을 몇 번 더 upvote 수 있다면, 나는 것이다. – Joshua

+1

Omg 나는이 대답을보기 전에 너무 많은 시간을 잃어 버렸다! +1 선생님 감사합니다! – avidenic

+2

이것은 오래되었지만 금색입니다. 젠장 도움이 – MihaiC

1

TLS/SSL을 통해 메시지를 보내려면 SmtpClient 클래스의 Ssl을 true로 설정해야합니다.

string to = "[email protected]"; 
string from = "[email protected]"; 
MailMessage message = new MailMessage(from, to); 
message.Subject = "Using the new SMTP client."; 
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily."; 
SmtpClient client = new SmtpClient(server); 
// Credentials are necessary if the server requires the client 
// to authenticate before it will send e-mail on the client's behalf. 
client.UseDefaultCredentials = true; 
client.EnableSsl = true; 
client.Send(message); 
+0

SSL 대 SMTP 클라이언트에 대한 몇 가지 코드 예제를 작성하여보다 나은 답변을 작성하십시오. –

관련 문제