Andrea Azzola

Tips and Techniques for Lifestyle Design

Search Email Inbox with C#

Posted on [Permalink]

A few years ago I helped managing a radio and I needed a tool—an ASP.NET web page—for the periodical download of promo mixes. They were linked in some emails recognizable by a few keywords.

The following, is the stripped down C# snippet from the tool, it demonostrate how to perform both the search inside the email's subject and body, and the download, with the use of the IMAP protocol:

using (ImapClient ic = new ImapClient("", "", "mypassword", 
    ImapClient.AuthMethods.Login, 993, true))
    MailMessage[] mm = ic.GetMessages(0, 100, false); // retrieves the latest 100 messages

    foreach (MailMessage m in mm)
        if (((m.From.Address == "") || (m.Body.ToLower().Contains("episode")))
            Regex regx = new Regex("(http|https)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@
            MatchCollection matches = regx.Matches(m.Body);

            Response.ContentType = "audio/mpeg3";
            Response.AddHeader("Content-Disposition", "attachment; filename=Episode.mp3");

            using (WebClient wc = new WebClient())


The script was based on the AE.NET.Mail library, which Andy Edinborough made free to use and it is available on his GitHub account.