0 votes
by (8.4k points)
edited

I have to write an application which will retrieve emails from the mail server. If message text includes the "message identification string" text than I need to extract message content and save it to the database. Only new messages should be processed. The mail server supports both POP3 and IMAP protocols. How to achieve it?

Applies to: Rebex Secure Mail

2 Answers

+1 vote
by (8.4k points)
edited
 
Best answer

It looks like Rebex Secure IMAP can do what you need. In C#, you might use a code like this:

// connect and log in
Imap imap = new Imap();
imap.Connect("imap.gmail.com", 993, null, ImapSecurity.Implicit);
imap.Login(username, password);

// go to inbox
imap.SelectFolder("Inbox");

// serch for e-mails that contain the expected text – get list of their IDs
ImapMessageCollection messages = imap.Search(
     ImapListFields.UniqueId, 
     ImapSearchParameter.Body("message identification string"),
     ImapSearchParameter.HasFlagsNoneOf(ImapMessageFlags.Seen)
);

// download each of the e-mails found, 
// retrieve its body and check whether it is the message you need
foreach (ImapMessageInfo info in messages)
{
    MailMessage mail = imap.GetMailMessage(info.UniqueId);
    string mailText = mail.BodyText;
    // search the string here, 
    // extract data you need and do what you need with it
 }
 imap.Disconnect();
+1 vote
by (13.0k points)
edited

In VB.NET, the code might look like this:

''# connect and log in
Dim imap As New Imap
imap.Connect("imap.gmail.com", 993, Nothing, ImapSecurity.Implicit)
imap.Login(username, password)

''# go to inbox
imap.SelectFolder("Inbox")

''# serch for e-mails that contain the expected text – get list of their IDs
Dim messages As ImapMessageCollection = imap.Search(_ 
     ImapListFields.UniqueId, _ 
     ImapSearchParameter.Body("Congratulations you have sold your product"), _
     ImapSearchParameter.HasFlagsNoneOf(ImapMessageFlags.Seen) _
)

''# download each of the e-mails found, 
''# retrieve its body and check whether it is the message you need
For Each info As ImapMessageInfo In messages

    Dim mail As MailMessage = imap.GetMailMessage(info.UniqueId)
    Dim mailText As String = mail.BodyText
    ''# search the string here, extract data you need and do what you need with it
Next

imap.Disconnect()
...