2010-04-21 5 views
2

전자 메일 목록을 보낼 때 SmtpClient의 SendCompletedEventHandler를 사용합니다.SmtpClient를 사용하여 메일 목록 보내기

SendCompletedEventHandler는 이미 목록에있는 모든 전자 메일을 보낸 경우에만 호출됩니다.

이메일을 보내면 SendCompletedEventHandler가 호출됩니다.

내 코드에 이상이 있습니까?

public void SendAllNewsletters(List<string> recipients) 
    { 
     string mailText = "My Text"; 
     foreach(string recipient in recipients) 
     { 
      //if this loop takes 10min then the first call to 
      //SendCompletedCallback is after 10min 
      SendNewsletter(mailText,recipient); 
     } 
    } 

    public bool SendNewsletter(string mailText , string emailaddress) 
    { 

      SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort); 
      System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword); 
      sc.Credentials = SMTPUserInfo; 
      sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); 

      MailMessage mm = null; 
      mm = new MailMessage(_senderemail, emailaddress); 
      mm.IsBodyHtml = true; 
      mm.Priority = MailPriority.Normal; 
      mm.Subject = "Something"; 
      mm.Body = mailText ; 
      mm.SubjectEncoding = Encoding.UTF8; 
      mm.BodyEncoding = Encoding.UTF8; 

      //Mail 
      string userState = emailaddress; 
      sc.SendAsync(mm, userState); 

      return true; 
    } 


    public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) 
    { 
     // Get the unique identifier for this asynchronous operation. 
     String token = (string)e.UserState; 
     if (e.Error != null) 
     { 
      _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message); 
     } 
     else 
     { 
      _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty); 
     }    
    } 

답변

1

당신은 (재 할당 핸들러를 다음과) SmtpClient 각각의 새로운 인스턴스 모든 시간을 만들 수 있습니다. 더 큰 범위의 정적 변수를 사용하십시오.

+0

처리기가 올바르지 않은 SmtpClient와 만 연결할 수 있다고 가정하는 것처럼 들립니다. 게다가 그는 매번 새로운 처리기를 만들어서 1 : 1 관계가 있습니다. –

0

내 컴퓨터에서 예상대로 작동합니다. "My Tex"은 유효한 전자 메일 주소가 아니기 때문에 MailMessage의 생성자에서 형식 예외가 발생합니다. 첫 번째 인수는 발신자의 전자 메일 주소입니다.

Josh Stodola가 지적했듯이 각 호출에 대해 다른 클래스를 생성하지 않고이 클래스의 수명 동안 SmtpClient을 캐시해야합니다. 당신이 SmtpClient를 캐시하지 않는 경우에, 당신은 (바람직하게는 finally 블록에서) SendCompletedCallback의 끝에 다음 줄을 추가해야합니다

((SmtpClient)sender).SendCompleted -= SendCompletedCallback; 

을이 도움이되지 않는 경우, 아마 당신은 게시 할 수있는 더 세부 정보 - 이벤트의 데이터가 무엇입니까? 을 수행하면이 호출됩니까?

+0

Thnx, MailMessage에 올바른 구문을 사용하도록 게시물을 업데이트했습니다. –

+0

그래도 문제가 해결 되었습니까? –

관련 문제