C#C
C#2y ago
3 replies
João Paulo

How can i detect a new e-mail arrival using GraphClientServer

I'm using Microsoft's outlook service through their graph library Microsoft.Graph.
I make a login request in an API and they send a security code to my company's email
I got stuck in the part of fetching my mailbox trying to find the security code e-mail.

Is there a common way of doing it? I was thinking about requesting the mail count in the inbox and loop wait until something happens. I looked through the docs and didn't find anything about an event-like thing

using (var timeout = Task.Delay(TimeSpan.FromMinutes(TIMEOUT_MAIL_WAIT_m)))
{
    while (timeout.IsCompleted is false)
    {
        string filter = $"receivedDateTime ge {DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ} and from/emailAddress/address eq '{emailAddress}'";
        var messages = await graphClient.Users[config.UserMailAddress].MailFolders.Inbox.Messages.Request().Filter(filter).GetAsync();

        foreach (var message in messages)
        {
            Console.WriteLine($"From: {message.From.EmailAddress.Address}, Subject: {message.Subject}");
        }

        if (Task.WhenAny(Task.Delay(TimeSpan.FromMinutes(1)), timeout) == timeout)
        {
            throw new TimeoutException("damn");
        }

    }
}
Was this page helpful?