0 votes
by (170 points)
edited

I wanna only check any new incoming emails and save any attachment to a folder. How to do it? Currently I could check my gmail inbox. My code is below

Try
    Dim client As New Imap
    client.Connect("imap.gmail.com", 993, Nothing, ImapSecurity.Implicit)
    client.Login(strUName, strPWD)

    client.SelectFolder("Inbox")

    'Label1.Text = client.CurrentFolder.RecentMessageCount
    If client.CurrentFolder.RecentMessageCount > 0 Then
        MessageBox.Show("You have new mail in your inbox!")
    End If


Catch ex As Exception
    MsgBox(ex.Message)
End Try
Applies to: Rebex Secure Mail

1 Answer

0 votes
by (70.2k points)
edited
 
Best answer

Please note that "Recent" messages are emails which arrived during your current session. Emails which arrived between your current session and last session are not marked as recent. Therefore you probably need to check "Unread" emails.

Following code should do the work:

Dim client As New Imap
client.Connect("imap.gmail.com", 993, Nothing, ImapSecurity.Implicit)
client.Login(strUName, strPWD)

client.SelectFolder("Inbox")

Dim list As ImapMessageCollection = client.Search( _
    ImapMessageSet.All, _
    ImapListFields.MessageStructure Or ImapListFields.UniqueId, _
    ImapSearchParameter.Unread)

For Each message As ImapMessageInfo In list
    If message.HasAttachment Then
        Dim mail As MailMessage = client.GetMailMessage(message.UniqueId)
        For Each attach As Attachment In mail.Attachments
            attach.Save(message.UniqueId & " - " & attach.FileName)
        Next
    End If
Next
by (170 points)
Thank you, Lukas. It works
...