2017-01-24 1 views
1

제 코딩에 도움이 필요합니다. 이메일에 메시지를 보내려고하지만 버튼을 클릭하고 메시지를 보내려고하면 오류가 계속 발생합니다. 오류 라인을 제공C# 메일 보내기/메시지/SMTP 오류

msg.To.Add(new MailAddress(txtBoxToEmail.Text)); 

유지 여기 중지 프로젝트로 :

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Net; 
using System.Net.Mail; 


namespace CO6009DissertationV5 
{ 

    public partial class frmSendMsg : Form 
    { 

     public frmSendMsg() 
     { 
      InitializeComponent(); 
     } 

     private void btnSend_Click(object sender, EventArgs e) 
     { 
      SmtpClient client = new SmtpClient(); 
      client.Host = "smtp.gmail.com"; 
      client.Port = 587; 
      client.EnableSsl = true; 

      System.Net.NetworkCredential userpassword = new System.Net.NetworkCredential(); 
      userpassword.UserName = "[email protected]"; 
      userpassword.Password = "password"; 

      client.Credentials = userpassword; 

      MailMessage msg = new MailMessage("[email protected]", "[email protected]"); 
      **msg.To.Add(new MailAddress(txtBoxToEmail.Text));** 
      msg.Body = "<b> Sender's Name: </b>" + txtBoxName.Text + "<p><b> Sender's E-mail: </b>" + txtBoxEmail.Text + "<p><b>Sender's Subject: </b>" + txtBoxSubject.Text + "<p><b>Sender's Message: </b>" + "<p>" + txtBoxMsg.Text; 
      msg.Subject = txtBoxSubject.Text; 
      msg.IsBodyHtml = true; 

      try 
      { 
       client.Send(msg); 
       lblMsgStatus.Text = "<p> Message Successfully Sent </p>"; 
      } 

      catch (Exception ex) 
      { 
       lblMsgStatus.Text = "Send failed"; 
      } 
     } 
    } 
} 

가장 큰 문제는이 선 것 같다 : 아래 코딩이

{ "매개 변수 '주소'는 빈 문자열 일 수 없습니다. \ r \ n 매개 변수 이름 : 주소 "}.

도움이 될만한 정보가 있으면 알려주세요. txtBoxToEmail.Text에 유효한 전자 메일 주소가

msg.To.Add(new MailAddress(txtBoxToEmail.Text)); 

없는 경우는, 시도 - 캐치와 코드를 포장하고 평가 예외 사항하시기 바랍니다 여전히 명확하지 않으면

+1

여기에 사용자/비밀번호로 코드를 붙여 넣지 마십시오! – Pikoh

+1

오류 메시지의 텍스트를 추가 할 수 있습니까? – Filburt

+0

[Gmail을 통해 .NET으로 이메일 보내기] (http://stackoverflow.com/q/32260/205233)를 확인하고 다른 많은 질문이 이미 있습니다. 이전에 누군가가 귀하의 오류를 만났을 가능성이 큽니다. – Filburt

답변

2

이 줄은 실패 할 수 있습니다

수정 : 나는 당신의 편집을보고, 나는 예외 메시지 "매개 변수 '주소'빈 문자열 수 없습니다. \ r \ n 매개 변수 이름 : 주소"꽤 분명하다 생각합니다.

0

메일을 보내기 전에 귀하의 EmailId를 확인하는 것이 좋습니다. 친절하게 방법 아래에 추가하고 다음과 같이 귀하의 버튼 클릭 이벤트에서 호출 :

 if (IsValidEmail(txtBoxToEmail.Text)) 
    { 
      msg.To.Add(new MailAddress(txtBoxToEmail.Text)); 
    } 

방법을 이메일 ID를 확인하기 :

static bool IsValidEmail(string email) 
    { 
     try 
     { 
      var addr = new System.Net.Mail.MailAddress(email); 
      return addr.Address == email; 
     } 
     catch 
     { 
      return false; 
     } 
    } 
+0

이것은 try/catch로 래핑 된 원래 코드와 동일한 것입니다. 이것은 어떤 종류의 유효성 검사도 수행하지 않습니다. OP는 이미 try/catch 블록에 코드를 래핑했습니다. –

+0

@ Panagiotis Kanavos 원본 코드에서 Null 체크를 할 수 있습니까? – Karthikeyan

+0

@ Panagiotis Kanavos 내가 게시 한 답변은 null을 확인합니다. – Karthikeyan

1

오류 메시지는 매우 분명하다 - 주소로 텍스트가 비어 있습니다. 이는 txtBoxToEmail.Text이 비어 있음을 의미합니다.

나중에 사용하기 전에 주소를 확인하여 이러한 문제를 피할 수 있습니다. 당신은 쉽게 예를 들어, String.IsNullOrWhitespace과 빈 문자열을 확인할 수 있습니다

private void btnSend_Click(object sender, EventArgs e) 
{ 
    if (String.IsNullOrWhitespace(txtBoxToEmail.Text)) 
    { 
     MessageBox.Show("To can't be empty!","Invalid Address", 
         MessageBoxButtons.OK,MessageBoxIcon.Error); 
     return; 
    } 
... 

당신은 텍스트가 @ 문자가 포함되어 있음을 보장하는 등 더 정교한 검사를 추가 할 수 있습니다.

더 나은 해결책은 컨트롤 및 폼 자체에 유효성 검사를 추가하여 사용자가 올바른 입력을 입력하지 않고 전자 메일을 보낼 수 없도록하는 것입니다.

Windows Forms는 User Input Validation in Windows Forms에서 설명한대로 입력을 확인하는 여러 가지 방법을 제공합니다.

txtBoxToEmailValidating 이벤트를 처리하여 올바른 주소를 확인하고 주소가 정확할 때까지 사용자가 제어 권한을 잃지 않도록 할 수 있습니다. 사실, 문서의 예제는 전자 메일 검증입니다! :

private void textBox1_Validating(object sender, 
       System.ComponentModel.CancelEventArgs e) 
{ 
    string errorMsg; 
    if(!ValidEmailAddress(textBox1.Text, out errorMsg)) 
    { 
     // Cancel the event and select the text to be corrected by the user. 
     e.Cancel = true; 
     textBox1.Select(0, textBox1.Text.Length); 

     // Set the ErrorProvider error with the text to display. 
     this.errorProvider1.SetError(textBox1, errorMsg); 
    } 
} 

private void textBox1_Validated(object sender, System.EventArgs e) 
{ 
    // If all conditions have been met, clear the ErrorProvider of errors. 
    errorProvider1.SetError(textBox1, ""); 
} 
public bool ValidEmailAddress(string emailAddress, out string errorMessage) 
{ 
    // Confirm that the e-mail address string is not empty. 
    if(String.IsNullOrWhitespace(emailAddress.Length)) 
    { 
     errorMessage = "e-mail address is required."; 
     return false; 
    } 

    // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order. 
    if(emailAddress.IndexOf("@") > -1) 
    { 
     if(emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@")) 
     { 
     errorMessage = ""; 
     return true; 
     } 
    } 

    errorMessage = "e-mail address must be valid e-mail address format.\n" + 
     "For example '[email protected]' "; 
     return false; 
} 

샘플 잘못된 입력 옆 느낌표 에러 UI를 표시 ErrorProvider 성분을 사용한다.

당신은 How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component

0

가 좋은 방법은 txtBoxToEmail.Text의 가치를 확인하고 있습니다에 ErrorProvider에 대한 자세한 정보를 찾을 수 있습니다. 어쩌면 null이거나 비어있을 수 있습니다. 그런 다음 .To.Add (new MailAddress (txtBoxToEmail.Text))를 사용하십시오.