Sunday, 5 November 2017

Reading the contents of emails in an inbox.

The .NET framework comes with a SMTP email client to send out emails in the box and is simple to use:

var msg = new MailMessage("oceanairdrop@gmail.com", toList, subject, messageBody);
var client = new SmtpClient(server).Send(msg);

But recently, I wanted to be able to read the contents of emails in an inbox. Thats when I went searching in the framework only to find out there there is no support for IMAP in the .NET framework. That's when I found Mailkit and its awesome!

Mailkit can query in inbox in all sorts of ways and works really well. That brings me to this blog post as its a mental bookmark for me if I ever need to do this kind of thing in the future.

To use it, there is nuget package you can use to pull down the library and easily include it in your project:

Install-Package MailKit 

Whats the code like? Well, here is an example of reading an inbox using the library:

using (var client = new ImapClient())
{
    client.ServerCertificateValidationCallback = (sndr, cert, chain, errors) => true;

    client.Connect("server", 993, true);
    client.Authenticate("username", "password");

    client.Inbox.Open(FolderAccess.ReadWrite);

    // The Inbox folder is always available on all IMAP servers...
    var inbox = client.Inbox;
    inbox.Open(FolderAccess.ReadOnly);

    Console.WriteLine("Total messages: {0}", inbox.Count);
    Console.WriteLine("Recent messages: {0}", inbox.Recent);

    // let's search for all messages received after 18/07/2017 with "Funny Joke" in the subject...
    var query = SearchQuery.DeliveredAfter(DateTime.Parse("2017-07-18"))
                           .And(SearchQuery.SubjectContains("Funny Joke"));

    foreach (var uid in inbox.Search(query))
    {
        var message = inbox.GetMessage(uid);
        Console.WriteLine("[match] {0}: {1}", uid, message.Subject);
    }

    foreach (var summary in inbox.Fetch(0, 10, MessageSummaryItems.Full | MessageSummaryItems.UniqueId))
    {
        Console.WriteLine("[summary] {0:D2}: {1}", summary.Index, summary.Envelope.Subject);
    }

    client.Disconnect(true);
}

Wow... That was easy! And here is an example of sending an email using the SMTP client in Mailkit:

using (var client = new MailKit.Net.Smtp.SmtpClient())
{
    client.Connect("server"); 
    client.Authenticate("username", "password");

    var messageToSend = new MimeMessage();
    messageToSend.From.Add(new MailboxAddress("Ocean Airdrop", "oceanairdrop@gmail.com"));
    messageToSend.To.Add(new MailboxAddress("Ocean Airdrop", "oceanairdrop@gmail.com"));
    messageToSend.Subject = "How you doin'?";

    messageToSend.Body = new TextPart("plain")
    {
        Text = @"some message goes here!"
    };

    client.Send(messageToSend);
    client.Disconnect(true);
}

Contact Me:  ocean.airdrop@gmail.com

Popular Posts

Recent Posts

Unordered List

Text Widget

Pages