Reputation: 2807
I have the following code to send emails to people, whose details are retrieved from a database:
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
The problem is that after it sends the first email, it gives me an COMException unhandled error, stating that the item has been moved or deleted. What is wrong here?
Upvotes: 1
Views: 953
Reputation: 300789
I believe you need a new outlook message each time through loop:
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
Upvotes: 1