+1 vote

I want to see an example where I could get only emails if the sender is from a specific email address. If it matches to download the email and attachment.

I have two senders that I would be monitoring, and then downloading the attachments.

by

1 Answer

0 votes
 
Best answer

There are 2 approaches:

First download basic email information which is fast and iterate over that:

imap.SelectInbox()
List<long> uids = imap.Search(Flag.Unseen);
List<MessageInfo> infos  = imap.GetMessageInfoByUID(uids);

iterate over infos checking MessageInfo.Envelope.From and add UIDs (MessageInfo.UID) to uidsToDownload collection.

Then you can download entire message:

List<long> uidsToDownload = ....

foreach (long uid in uidsToDownload)
{
    IMail email = new MailBuilder()
        .CreateFromEml(imap.GetMessageByUID(uid));

    Console.WriteLine(email.Subject);

    // save all attachments to disk
    foreach(MimeData mime in email.Attachments)
    {
        mime.Save(mime.SafeFileName);
    }
}

Second approach is to relay on IMAP server search entirely:

List<long> uids = imap.Search().Where(
    Expression.And(
        Expression.HasFlag(Flag.Unseen),
        Expression.Or(
            Expression.From("test1@example.com"),
            Expression.From("test2@example.com")
            )
        )
    );

Some links to the samples:

https://www.limilabs.com/blog/get-email-information-from-imap-fast

https://www.limilabs.com/blog/download-email-attachments-net

https://www.limilabs.com/blog/how-to-search-imap-in-net

by (297k points)
...