使用VB.Net通过Outlook发送电子邮件时出现COMException未处理错误

时间:2011-03-25 04:35:18

标签: vb.net outlook comexception

我有以下代码向人们发送电子邮件,其详细信息从数据库中检索到:

Dim oMsg As Outlook._MailItem
Dim objOL As Outlook.Application
objOL = New Outlook.Application()
oMsg = objOL.CreateItem(Outlook.OlItemType.olMailItem)

con = New OleDbConnection("provider=SQLOLEDB;data source=pc;initial catalog=DB1;integrated security=SSPI")
cmd = New OleDbCommand("select column1, column2, column3, column4 from table1 where <condition>", con)
con.Open()
r = cmd.ExecuteReader
While r.Read
    oMsg.Subject = "Subject"
    oMsg.Body = "Hello " & r.Item(0) & vbLf & vbCr & "How are " & r.Item(1) & " and" & r.Item(2) & vbLf & vbCr & " ? "
    oMsg.To = r.Item(3).ToString
    oMsg.Send()
End While
con.Close()
oMsg = Nothing
objOL = Nothing

问题是,在发送第一封电子邮件后,它会给我一个未处理的COMException错误,说明该项已被移动或删除。这有什么不对?

1 个答案:

答案 0 :(得分:1)

我相信每次循环都需要一条新的Outlook消息:

Dim oMsg As Outlook._MailItem 
Dim objOL As Outlook.Application 
objOL = New Outlook.Application() 

con = New OleDbConnection("provider=SQLOLEDB;data source=pc;initial catalog=DB1;integrated security=SSPI") 
cmd = New OleDbCommand("select column1, column2, column3, column4 from table1 where <condition>", con) 
con.Open() 
r = cmd.ExecuteReader 
While r.Read 
    oMsg = objOL.CreateItem(Outlook.OlItemType.olMailItem) 

    oMsg.Subject = "Subject" 
    oMsg.Body = "Hello " & r.Item(0) & vbLf & vbCr & "How are " & r.Item(1) & " and" & r.Item(2) & vbLf & vbCr & " ? " 
    oMsg.To = r.Item(3).ToString 
    oMsg.Send() 

    oMsg = Nothing 
End While 
con.Close() 
objOL = Nothing