Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MailKit : Obtaining new mail notification from IMAP server

Tags:

c#

imap

mailkit

I need to create a service (or console) app that connects to an IMAP server and listens for new mail. I'm currently trying to use MailKit but I'm having trouble trying to figure out how to accomplish this from the documentation.

The closest I've come is from this post. From what I can see, this post is setting the connection into IDLE mode and occasionally sending NoOP to try to keep the connection alive. What isn't entirely clear to me is how to receive the new mail notification.

The MailKit documentation seems to indicate that there is an Alert event available. I've tried hooking into that but that doesn't seem to fix anything.

Here is what I've tried:

    var cts = new CancellationTokenSource();
    testIDLEMailNotification(cts.Token);

    ...

    private static void testIDLEMailNotification(CancellationToken token)
    {
        using (var client = ClientCreateAndConnect(token))
        {
            while(!token.IsCancellationRequested)
            {
                using (var done = new CancellationTokenSource())
                {
                    using (var timer = new System.Timers.Timer(9 * 60 * 1000))
                    {
                        timer.Elapsed += (sender, e) => done.Cancel();
                        timer.AutoReset = false;
                        timer.Enabled = true;
                        try
                        {
                            client.Idle(done.Token, token);
                            client.NoOp(token);

                        }
                        catch (OperationCanceledException)
                        {
                            break;
                        }
                    }
                }
            }
        }
    }

    private static ImapClient ClientCreateAndConnect(CancellationToken token)
    {
        var client = new ImapClient();
        client.Connect("server.domain", 993, true, token);
        client.AuthenticationMechanisms.Remove("XOAUTH");
        client.Authenticate("[email protected]", "password",token);

        client.Inbox.Open(MailKit.FolderAccess.ReadWrite, token);
        client.Alert += client_Alert;
        return client;
    }

    static void client_Alert(object sender, AlertEventArgs e)
    {
        Console.WriteLine("New Email or something.");
    }
like image 659
RHarris Avatar asked Nov 27 '22 07:11

RHarris


1 Answers

I found a sample here. I kept looking on the IMAPClient for some sort of event and there weren't any specifically relating to message notification.

However, as the sample shows, the events are on the IMAPFolder class ... which makes sense now that I think about it.

Hope this helps someone else.

like image 120
RHarris Avatar answered Dec 18 '22 15:12

RHarris