문제

전자 메일을 비동기로 보내려고 노력하고 있으며 이메일에 첨부 된 대체보기가없는 한 잘 작동합니다. 대체보기가 있으면 다음 오류가 발생합니다.

Cannot access a disposed object. Object name: 'System.Net.Mail.AlternateView'
System.Net.Mail.SmtpException: Failure sending mail. ---> System.ObjectDisposedException: Cannot access a disposed object.

Object name: 'System.Net.Mail.AlternateView'.
   at System.Net.Mail.AlternateView.get_LinkedResources()
   at System.Net.Mail.MailMessage.SetContent()
   at System.Net.Mail.MailMessage.BeginSend(BaseWriter writer, Boolean sendEnvelope, AsyncCallback callback, Object state)
   at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)

다음은 샘플 코드입니다.

Dim msg As New System.Net.Mail.MailMessage
msg.From = New System.Net.Mail.MailAddress("me@example.com", "My Name")
msg.Subject = "email subject goes here"

'add the message bodies to the mail message
Dim hAV As System.Net.Mail.AlternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(textBody.ToString, Nothing, "text/plain")
hAV.TransferEncoding = Net.Mime.TransferEncoding.QuotedPrintable
msg.AlternateViews.Add(hAV)

Dim tAV As System.Net.Mail.AlternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(htmlBody.ToString, Nothing, "text/html")
tAV.TransferEncoding = Net.Mime.TransferEncoding.QuotedPrintable
msg.AlternateViews.Add(tAV)

Dim userState As Object = msg
Dim smtp As New System.Net.Mail.SmtpClient("emailServer")

'wire up the event for when the Async send is completed
 AddHandler smtp.SendCompleted, AddressOf SmtpClient_OnCompleted

 Try
     smtp.SendAsync(msg, userState)
 Catch '.... perform exception handling, etc...
 End Try

그리고 콜백 .....

 Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
    If e.Cancelled Then
      'Log the cancelled error
    End If
    If Not IsNothing(e.Error) Then
        'Log a real error....
        ' this is where the error is getting picked up
    End If

    'dispose the message
    Dim msg As System.Net.Mail.MailMessage = DirectCast(e.UserState, System.Net.Mail.MailMessage)
    msg.Dispose()

End Sub
도움이 되었습니까?

해결책

이것이 작동하지 않는 이유는 sendasync () 메소드가 완료되면 oncompleted 핸들러가 호출되기 때문입니다. 그러나 SMTPClient가 네트워크에서 이메일을 물리적으로 전송하기 전에 보이는 것처럼 보입니다 (네트워크 전달에만 해당됩니다. 파일 배달은 본질적으로 sendasync ()와 동기입니다.

oncompleted는 메시지가 실제로 전송 된 경우에만 호출되어야하기 때문에 SMTPClient의 버그처럼 보입니다.

다른 팁

나는 매우 유사한 문제가있었습니다. 동일한 오류 메시지이지만 약간 다른 코드 구조입니다. 제 경우에는 기본 함수 내부의 우편물 객체를 처분했습니다. oncompleted 이벤트가 실행될 때, 객체는 이미 사라졌습니다.

sendasync 후 코드를보고 MailMessage 객체를 제거하고 있는지 확인하십시오. 예를 들어, 사용 명령문 내에서 작성하는 경우 비동기 이벤트가 실행되기 전에 해제됩니다.

콜백에서 액세스하려면 클래스 레벨에 딤스를 넣어야합니다.

private msg As System.Net.Mail.MailMessage
private hAV As System.Net.Mail.AlternateView 

private sub yoursub
  msg = new System.Net.Mail.MailMessage(..
  hAV = new ...
end sub

내 추측은 AlternateViews.add는 단지 HAV의 참조를 추가하면 MSG 객체는 GC에 의해 자동으로 배치되는 동안 MSG 객체를 폐기해야합니다.

건배

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top