我试图异步发送电子邮件,并且只要电子邮件没有附加访问浏览量即可。当有其他视图时,我会收到以下错误:

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()方法完成时,您可以调用您的迎接处理程序,但这似乎是在SMTPCLEINT完成在整个网络上实际发送电子邮件之前(但是,只有网络交付才会发生,但是文件传递本质上与sendAsync())同步。

这几乎是SMTPCLIENT中的一个错误,因为仅在消息真正发送时,才能真正调用。

其他提示

我有一个非常相似的问题。相同的错误消息,但代码结构略有不同。就我而言,我将MailMessage对象处置为主函数。到了迎面而已的事件运行时,对象已经消失了。

在SendAsync之后查看您的代码,以查看您是否正在释放MailMessage对象。例如,如果要在使用语句中创建它,则将在运行异步事件之前将其释放。

如果要在回调中访问它们,则应将DIM放在班级级别上。

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

我的猜测是,备份浏览。ADD仅添加了HAV的引用,MSG对象需要处置,而GC自动处理HAV。

干杯

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top