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("imap.gmail.com", "gmail@gmail.com", "mypassword", 
    ImapClient.AuthMethods.Login, 993, true))
{
    ic.SelectMailbox("INBOX");
    MailMessage[] mm = ic.GetMessages(0, 100, false); // retrieves the latest 100 messages

    foreach (MailMessage m in mm)
        if (((m.From.Address == "foo@bar.com") || (m.Body.ToLower().Contains("episode")))
        {
            Regex regx = new Regex("(http|https)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@
\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", 
                RegexOptions.IgnoreCase);
            MatchCollection matches = regx.Matches(m.Body);

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

            using (WebClient wc = new WebClient())
                Response.BinaryWrite(wc.DownloadData(matches[0].Value));

            Response.End();
        }
}

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.

Categories: