2014-01-18 2 views
1

응용 프로그램에서는 Send가 아닌 SendAsync를 사용해야합니다. 그래서 나는 CEmailServer 클래스를 만들고 모든 것을 설정했다. 지금까지 Send는 정상적으로 작동하지만 SendAsync와 함께 작동하도록 변경하면 Send가 작동하지 않습니다. 메일을 보내고 userToken을 제자리에 놓았지만 실패 할 때 호출 할 메서드를 만들었습니다. 나는 내 오류를 찾을 수 없다. 내 코드는 다음과 같습니다.SendAsync Smtp 메일 오류

static bool mailSent = false; 

//Method for Sending with attachment. 
public void SendEmail(string Address, string Recipient, string Subject, string Body, string Dir) 
{ 
    var fromAddress = new MailAddress("[email protected]", "My Company"); 
    var toAddress = new MailAddress(Address, Recipient); 
    const string fromPassword = "password"; 
    string subject = Subject; 
    string body = Body; 

    var smtp = new SmtpClient 
    { 
     Host = "smtp.gmail.com", 
     Port = 587, 
     EnableSsl = true, 
     DeliveryMethod = SmtpDeliveryMethod.Network, 
     UseDefaultCredentials = false, 
     Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 

    }; 
    using (var message = new MailMessage(fromAddress, toAddress) 
    { 
     Subject = subject, 
     Body = body, 
    }) 
    { 
     smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); 
     string userState = "Test"; 
     message.Attachments.Add(new Attachment(Dir)); 
     smtp.SendAsync(message,userState); 
     message.Dispose(); 
    } 
} 

//Method for Sending regular message without attachment. 
public void SendEmail(string Address, string Recipient, string Subject, string Body) 
{ 
    var fromAddress = new MailAddress("[email protected]", "My Company"); 
    var toAddress = new MailAddress(Address, Recipient); 
    const string fromPassword = "password"; 
    string subject = Subject; 
    string body = Body; 

    var smtp = new SmtpClient 
    { 
     Host = "smtp.gmail.com", 
     Port = 587, 
     EnableSsl = true, 
     DeliveryMethod = SmtpDeliveryMethod.Network, 
     UseDefaultCredentials = false, 
     Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 

    }; 
    using (var message = new MailMessage(fromAddress, toAddress) 
    { 
     Subject = subject, 
     Body = body, 
    }) 
    { 
     smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); 
     string userState = "Message Sent"; 
     smtp.SendAsync(message, userState); 
     message.Dispose(); 
    } 
} 

//Method to be called when sending is complete 
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) 
{ 
    // Get the unique identifier for this asynchronous operation. 
    String token = (string)e.UserState; 

    if (e.Cancelled) 
    { 
     MessageBox.Show("Sending Canc"); 
    } 
    if (e.Error != null) 
    { 
     MessageBox.Show("Error Sending Mail"); 
    } 
    else 
    { 
     MessageBox.Show("Message sent."); 
    } 
    mailSent = true; 
} 

대단히 고마워요!

+0

나는 진심으로 그 실제 암호가 아닙니다 바랍니다. –

+0

아니, 오래된 aacount thats 삭제되었습니다 – Mordacai1000

+0

경우에만 다른 자격 증명을 사용하십시오 :) – Mordacai1000

답변

6

보내기가 완료되기 전에 message을 삭제 중입니다. 너는 SendCompleted 콜백 이벤트에 그들을 처리해야합니다. 클라이언트와 메시지를 처리하는 가장 좋은 방법은 example입니다.

코드는 다음과 같이 보일 것이다 :

var smtp = new SmtpClient 
{ 
    Host = "smtp.gmail.com", 
    Port = 587, 
    EnableSsl = true, 
    DeliveryMethod = SmtpDeliveryMethod.Network, 
    UseDefaultCredentials = false, 
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 
}; 

var message = new MailMessage(fromAddress, toAddress) 
{ 
    Subject = subject, 
    Body = body, 
}; 

smtp.SendCompleted += (s, e) => { 
    SendCompletedCallback(s, e); 
    smtp.Dispose(); 
    message.Dispose(); 
}; 
string userState = "Test"; 
message.Attachments.Add(new Attachment(Dir)); 
smtp.SendAsync(message, userState); 
+0

내가 Dispose 메서드 호출을 제거했지만 여전히 작동하지 않습니다 ... – Mordacai1000

+1

@ Mordacai1000'message'를 '진술도? 또한 예외의 세부 사항을 제공 할 수 있다면 도움이 될 것입니다. –

+0

메시지를 삭제하지 않았습니다. 다음은 오류입니다. System.Net.Mail.SmtpException : 메일을 보내지 못했습니다. ---> System.ObjectDisposedException : 폐기 된 개체에 액세스 할 수 없습니다. 개체 이름 : 'System.Net.Mail.MailMessage'. System.Net.Mail.SmtpClient.SendMailCallback에서 System.Net.Mail.MailMessage.SetContent (부울 allowUnicode) 에서 System.Net.Mail.MailMessage.get_AlternateViews() (IAsyncResult를 결과) --- 내부의 끝에 예외 스택 추적 --- – Mordacai1000