Saturday, March 03, 2007

CDO for receiving emails via SMTP

I recently discovered that .NET 2.0 does not have an inbuilt class for receiving emails via SMTP (or by any other means). Surprising omission. I started to write my own email file parser, but then had a thought... Why not use the old CDO (aka CDOSYS) like the old ClassicASP days? This is how to do it...

Create a reference in Visual Studio to Microsoft CDO for Windows 2000. Now use some code like this:

Dim objSMTP As New System.Net.Mail.SmtpClient
Dim strMailbox As String = objSMTP.PickupDirectoryLocation.Substring(0, objSMTP.PickupDirectoryLocation.LastIndexOf("\")) & "\Mailbox"
Dim CDODropDir As New CDO.DropDirectory
Dim CDOMessages As CDO.IMessages = CDODropDir.GetMessages(strMailbox)
Dim CDOMessage As CDO.Message
For Each CDOMessage In CDOMessages
'Some useful properties:
'CDOMessage.To, CDOMessage.CC, CDOMessage.BCC, CDOMessage.From
'CDOMessage.ReceivedTime, CDOMessage.Subject
'CDOMessage.TextBody, CDOMessage.HTMLBody
'CDOMessages.FileName(CDOMessage) '--Useful for deleting messages later (after you read the whole collection first!)
Next

No comments: