private async void GetRogreenHighImportanceMessagesButton_Click(Object sender, RoutedEventArgs e)
        {
            try
            {
                string filter = "importance eq 'high' " +
                                "and sender/emailaddress/address eq '*****@*****.**'";
                folderMessages = await graphClient.Me.MailFolders.Inbox.Messages.Request()
                                 .Filter(filter).GetAsync();

                MyMessages = new ObservableCollection <Models.Message>();

                foreach (var message in folderMessages)
                {
                    MyMessages.Add(new Models.Message
                    {
                        Id     = message.Id,
                        Sender = (message.Sender != null) ?
                                 message.Sender.EmailAddress.Name :
                                 "Unknown name",
                        From = (message.Sender != null) ?
                               message.Sender.EmailAddress.Address :
                               "Unknown email",
                        Subject    = message.Subject ?? "No subject",
                        Importance = message.Importance.ToString()
                    });
                }

                MessageCountTextBlock.Text   = $"You have {MyMessages.Count()} red bang messages:";
                MessagesDataGrid.ItemsSource = MyMessages;
            }
            catch (ServiceException ex)
            {
                MessageCountTextBlock.Text = $"We could not get messages: {ex.Error.Message}";
            }
        }
        public async Task <List <Message> > GetRecentUnreadMail()
        {
            var graphClient = GetAuthenticatedClient();
            IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();

            DateTime       from           = DateTime.Now.Subtract(TimeSpan.FromMinutes(30));
            List <Message> unreadMessages = new List <Message>();

            var done = false;

            while (messages?.Count > 0 && !done)
            {
                foreach (Message message in messages)
                {
                    if (message.ReceivedDateTime.HasValue && message.ReceivedDateTime.Value >= from)
                    {
                        if (message.IsRead.HasValue && !message.IsRead.Value)
                        {
                            unreadMessages.Add(message);
                        }
                    }
                    else
                    {
                        done = true;
                    }
                }

                messages = await messages.NextPageRequest.GetAsync();
            }

            return(unreadMessages);
        }
示例#3
0
 private void OutputMessages(IMailFolderMessagesCollectionPage messages)
 {
     foreach (var message in messages)
     {
         var output = $"Message: {message.Id} {message.Subject} {message.Body}";
         Console.WriteLine(output);
     }
 }
示例#4
0
        public async Task <List <Message> > ListSentMessages(string fparam1)
        {
            List <ResultsItem> items = new List <ResultsItem>();

            List <QueryOption> options = new List <QueryOption>()
            {
                new QueryOption("filter", "folder ne null"),
                new QueryOption("select", "id,name,webUrl")
            };

            IMailFolderMessagesCollectionPage messages = await _graphClient.Users[userid].MailFolders.SentItems.Messages.Request().Top(100).GetAsync();

            return(messages.ToList().Where(i => i.Subject.ToLower().Contains(fparam1)).ToList <Message>());
        }
示例#5
0
        public static async Task <IMailFolderMessagesCollectionPage> GetNextMessages(IMailFolderMessagesCollectionPage messages)
        {
            try
            {
                if (messages.NextPageRequest == null)
                {
                    return(null);
                }

                return(await messages.NextPageRequest.GetAsync());
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting messages: {ex.Message}");
                return(null);
            }
        }
        // Get messages with attachments in the current user's inbox.
        public async Task <List <ResultsItem> > GetMyInboxMessagesThatHaveAttachments()
        {
            List <ResultsItem> items = new List <ResultsItem>();

            // Get messages in the Inbox folder that have attachments.
            // Note: Messages that have inline messages don't set the `hasAttachments` property to `true`. To find them, you need to parse the body content.
            IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request(requestOptions)
                                                         .WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount())
                                                         .Filter("hasAttachments eq true")
                                                         .Expand("attachments")
                                                         .GetAsync();

            if (messages?.Count > 0)
            {
                foreach (Message message in messages)
                {
                    // This snippet displays information about the first attachment and displays the content if it's an image.
                    // Reference attachments include a file attachment as a file-type icon.
                    Attachment firstAttachment = message.Attachments[0];
                    byte[]     contentBytes    = null;
                    if ((firstAttachment is FileAttachment) && (firstAttachment.ContentType.Contains("image")))
                    {
                        FileAttachment fileAttachment = firstAttachment as FileAttachment;
                        contentBytes = fileAttachment.ContentBytes;
                    }

                    items.Add(new ResultsItem
                    {
                        Display    = message.Subject,
                        Id         = message.Id,
                        Properties = new Dictionary <string, object>
                        {
                            { Resource.Prop_AttachmentsCount, message.Attachments.Count },
                            { Resource.Prop_AttachmentName, firstAttachment.Name },
                            { Resource.Prop_AttachmentType, firstAttachment.ODataType },
                            { Resource.Prop_AttachmentSize, firstAttachment.Size },
                            { "Stream", contentBytes }
                        }
                    });
                }
            }
            return(items);
        }
示例#7
0
        public async Task <List <ResultsItem> > ListInboxMessages(string alias)
        {
            User user = FindByAlias(alias).Result;
            List <ResultsItem> items = new List <ResultsItem>();

            IMailFolderMessagesCollectionPage messages = await _graphClient.Users[user.Id].MailFolders.Inbox.Messages.Request().Top(10).GetAsync();

            if (messages?.Count > 0)
            {
                foreach (Message message in messages)
                {
                    items.Add(new ResultsItem
                    {
                        Display = message.Subject,
                        Id      = message.Id
                    });
                }
            }
            return(items);
        }
        // Get messages in the current user's inbox.
        // To get the messages from another mail folder, you can specify the Drafts, DeletedItems, or SentItems well-known folder,
        // or you can specify the folder ID, for example: `await graphClient.Me.MailFolders[folder-id].Messages.Request().GetAsync();`
        public async Task <List <ResultsItem> > GetMyInboxMessages(GraphServiceClient graphClient)
        {
            List <ResultsItem> items = new List <ResultsItem>();

            // Get messages in the Inbox folder.
            IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();

            if (messages?.Count > 0)
            {
                foreach (Message message in messages)
                {
                    items.Add(new ResultsItem
                    {
                        Display = message.Subject,
                        Id      = message.Id
                    });
                }
            }
            return(items);
        }
示例#9
0
        /// <summary>
        /// MEthod for fetching the Inbox messages
        /// </summary>
        /// <param name="userid">Messages from which user</param>
        /// <param name="searchparam1">filter parameter for the subject</param>
        /// <returns></returns>
        public async Task <List <Message> > ListInboxMessages(string searchparam)
        {
            //List<ResultsItem> items = new List<ResultsItem>();

            IMailFolderMessagesCollectionPage messages = await _graphClient.Users[userid].MailFolders.Inbox.Messages.Request().Top(100).GetAsync();

            //List<Message> fmsgs = messages.ToList<Message>().Where(i => i.Subject.ToLower().Contains(searchparam)).ToList<Message>();
            //if (messages?.Count > 0)
            //{
            //    foreach (Message message in messages)
            //    {
            //        items.Add(new ResultsItem
            //        {
            //            Subject = message.Subject,
            //            Id = message.Id
            //        });
            //    }
            //}

            return(messages.ToList().Where(i => i.Subject.ToLower().Contains(searchparam)).ToList <Message>());
        }
示例#10
0
        public async Task <IActionResult> Index()
        {
            string token = "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFEQ29NcGpKWHJ4VHE5Vkc5dGUtN0ZYU3dTSEFKZzN0S3g0WGYzZjg1TDNhc2pnQ0o4c3ZxVXBQVi1PNWI0SVNVRHhpcmcycHhmMUJ2YjBCbzQ1QjE1S3czYTBUM0V1bnBhZXJma3hOY0xTX0NBQSIsImFsZyI6IlJTMjU2IiwieDV0IjoiQ3RmUUM4TGUtOE5zQzdvQzJ6UWtacGNyZk9jIiwia2lkIjoiQ3RmUUM4TGUtOE5zQzdvQzJ6UWtacGNyZk9jIn0.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC85ZjFhMGZlMi1iMTY4LTQyMjgtYjM0Yi04NWRjNjQ2ZmE3NTMvIiwiaWF0IjoxNTYwMzQyMDkwLCJuYmYiOjE1NjAzNDIwOTAsImV4cCI6MTU2MDM0NTk5MCwiYWNjdCI6MCwiYWNyIjoiMSIsImFpbyI6IkFTUUEyLzhMQUFBQTBpUGt1NTdYUGo3UjNuUFZiZFh4a0ZOcUJQdkd4K1lGWU83WC9iakU5RFk9IiwiYW1yIjpbInB3ZCJdLCJhcHBfZGlzcGxheW5hbWUiOiJFbWFpbExvZ2dpbmctQWRkLUluIiwiYXBwaWQiOiJhNjQ0MmE1NC1jZTVhLTQwOWEtOWI4NS03Y2EyMmU2NDhjYmMiLCJhcHBpZGFjciI6IjAiLCJmYW1pbHlfbmFtZSI6IlBhbmNoYWwiLCJnaXZlbl9uYW1lIjoiVmFzdSIsImlwYWRkciI6IjE4MC4yMTEuMTAzLjE4NSIsIm5hbWUiOiJWYXN1IFBhbmNoYWwiLCJvaWQiOiJiN2NlMzhmNy1hNGRlLTRhNzgtYTdhNS0wNWJhZmQ2ZDcyMjUiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzIwMDA0MkE2NTE3OSIsInNjcCI6IkZpbGVzLlJlYWRXcml0ZS5BbGwgTWFpbC5SZWFkIG9wZW5pZCBwcm9maWxlIFNpdGVzLlJlYWQuQWxsIFVzZXIuUmVhZCBlbWFpbCIsInNpZ25pbl9zdGF0ZSI6WyJpbmtub3dubnR3ayJdLCJzdWIiOiJ2Z0pKaU1oZFdOMjJyQjA4QXBON0pkVXlxRk5wT3NUdGRjQWtDUmpfM2E0IiwidGlkIjoiOWYxYTBmZTItYjE2OC00MjI4LWIzNGItODVkYzY0NmZhNzUzIiwidW5pcXVlX25hbWUiOiJ2YXN1QHByYWthc2hpbmZvdGVjaC5jb20iLCJ1cG4iOiJ2YXN1QHByYWthc2hpbmZvdGVjaC5jb20iLCJ1dGkiOiJUc0dXdlhtd18wS0hRNjl0YmIwbUFBIiwidmVyIjoiMS4wIiwieG1zX3N0Ijp7InN1YiI6Ilh6aHNzVHBZbmNObUZjbkxoQ1hrZHMwSERoeUNFXzJNV0NObVl0aktfTVkifSwieG1zX3RjZHQiOjEzMzgzNjAyNTR9.NdaOhi4jVmg0IwmmczbmkOQriEdm3BxPShvc9WsLCAcNDg1TCgc2RuycBboHLlRS36zft9f3LBpyfYjEdmb-Gwb6Ndce-hsDqyN6h4WuRNZEIN3QZ37I2qsiTvPp8-mRBhlDWyKgUNvaJ98zFTPo1WhtivcevBhl6yPVh9c2RNcs91UTq-3K7t8Ea54_6XmKj65zRJ0PLGUrbt_4u1cDtzl8uD9eD5KAyZr6adINoZkr_kj--95VZR_XlPqGFKy24dNm0LSUYR2MmflsJ5f2cORKZh3FAi7E4s9br-oWWTscQjnYH_fc4luAF8zpV8u7SlPAvDYRv4fsm7F6drks8A";

            if (string.IsNullOrEmpty(token))
            {
                // If there's no token in the session, redirect to Home
                return(Redirect("/"));
            }
            try
            {
                //Creating Request Graph Client with Authorization Token
                GraphServiceClient client = new GraphServiceClient(
                    new DelegateAuthenticationProvider(
                        (requestMessage) =>
                {
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", token);

                    return(Task.FromResult(0));
                }));

                //Getting Top (2) Emails with Attachments from SentItems
                IMailFolderMessagesCollectionPage mailResults = await client.Me.MailFolders.SentItems.Messages.Request().Expand("attachments").Top(2).GetAsync();


                List <EmailBuilderViewModel> EviewModel = FillEmailModel(mailResults);

                GraphModel md = new GraphModel();
                md.EmailItems = EviewModel;

                GenerateEmail(md.EmailItems);

                return(View(md));
            }
            catch (System.Exception ex)
            {
                return(RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message }));
            }
        }
        // Get messages in the current user's inbox.
        // To get the messages from another mail folder, you can specify the Drafts, DeletedItems, or SentItems well-known folder,
        // or you can specify the folder ID, for example: `await graphClient.Me.MailFolders[folder-id].Messages.Request().GetAsync();`
        public async Task <List <ResultsItem> > GetMyInboxMessages()
        {
            List <ResultsItem> items = new List <ResultsItem>();

            // Get messages in the Inbox folder.
            IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request(requestOptions)
                                                         .WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount())
                                                         .GetAsync();

            if (messages?.Count > 0)
            {
                foreach (Message message in messages)
                {
                    items.Add(new ResultsItem
                    {
                        Display = message.Subject,
                        Id      = message.Id
                    });
                }
            }
            return(items);
        }
示例#12
0
        /// <summary>
        /// Binds Email Message to EmailBuilderViewModel Model
        /// </summary>
        /// <param name="mailResults">IMailFolderMessagesCollectionPage response from Graph API Request</param>
        /// <returns>List of EmailBuilderViewModel</returns>
        private List <EmailBuilderViewModel> FillEmailModel(IMailFolderMessagesCollectionPage mailResults)
        {
            List <EmailBuilderViewModel> EviewModel = new List <EmailBuilderViewModel>();

            foreach (Message msg in mailResults)
            {
                EviewModel.Add(new EmailBuilderViewModel
                {
                    Id      = msg.Id,
                    Subject = msg.Subject ?? string.Empty,
                    Sender  = msg.Sender.EmailAddress.Address.ToString() ?? string.Empty,
                    From    = msg.From.EmailAddress.Address.ToString() ?? string.Empty,
                    Body    = msg.Body.Content.ToString() ?? string.Empty,

                    EmailAttachemnets = msg.Attachments.Select(x => new EmailAttachment
                    {
                        AttachmentID = msg.Attachments.CurrentPage.Select(z => z.Id).FirstOrDefault(),
                        Name         = msg.Attachments.CurrentPage.Select(z => z.Name).FirstOrDefault(),
                        ContentType  = msg.Attachments.CurrentPage.Select(z => z.ContentType).FirstOrDefault(),
                        Size         = msg.Attachments.CurrentPage.Select(z => z.Size).FirstOrDefault(),
                        File         = msg.Attachments.CurrentPage.Cast <FileAttachment>().Select(z => z.ContentBytes).FirstOrDefault(),
                    }).ToList(),

                    ToRecipients  = msg.ToRecipients.Select(x => x.EmailAddress.Address).ToList <string>(),
                    BccRecipients = msg.BccRecipients.Select(x => x.EmailAddress.Address).ToList <string>(),
                    CcRecipients  = msg.CcRecipients.Select(x => x.EmailAddress.Address).ToList <string>(),

                    hasAttachments    = msg.HasAttachments,
                    CreatedDateTime   = msg.CreatedDateTime,
                    SentDateTime      = msg.SentDateTime,
                    ConversationId    = msg.ConversationId,
                    InternetMessageId = msg.InternetMessageId,
                    ParentFolderId    = msg.ParentFolderId,
                    WebLink           = msg.WebLink,
                });
            }
            return(EviewModel);
        }
        private async void GetInboxMessagesButton_Click(Object sender, RoutedEventArgs e)
        {
            try
            {
                // Get only messages from my Inbox
                inbox = await graphClient.Me.MailFolders.Inbox.Request().GetAsync();

                folderMessages = await graphClient.Me.MailFolders.Inbox.Messages.Request()
                                 .Top(20).GetAsync();

                MyMessages = new ObservableCollection <Models.Message>();

                foreach (var message in folderMessages)
                {
                    MyMessages.Add(new Models.Message
                    {
                        Id     = message.Id,
                        Sender = (message.Sender != null) ?
                                 message.Sender.EmailAddress.Name :
                                 "Unknown name",
                        From = (message.Sender != null) ?
                               message.Sender.EmailAddress.Address :
                               "Unknown email",
                        Subject    = message.Subject ?? "No subject",
                        Importance = message.Importance.ToString()
                    });
                }

                MessageCountTextBlock.Text = $"You have {inbox.TotalItemCount} messages, " +
                                             $"{inbox.UnreadItemCount} of them are unread. Here are the first 20:";
                MessagesDataGrid.ItemsSource = MyMessages;
            }
            catch (ServiceException ex)
            {
                MessageCountTextBlock.Text = $"We could not get messages: {ex.Error.Message}";
            }
        }
        /// <summary>
        /// Given a set of messages, this function iterates through them
        /// and saves (to either OneDrive or Google Drive), deletes, and embeds a hyperlink to attachment location
        /// </summary>
        /// <returns> Returns true if attachments were successfully cleaned </returns>
        internal static async Task <bool> cleanupMessages(IMailFolderMessagesCollectionPage messages, GraphServiceClient graphClient, string accessToken, string callbackToken, string requestUri)
        {
            EmailController control = new EmailController();


            foreach (var message in messages.CurrentPage)
            {
                if ((message.HasAttachments != null && message.HasAttachments == true) || (Format.getBetween(message.Body.Content.ToString(), "<img", ">") != ""))
                {
                    var attachments = await graphClient.Me.Messages[message.Id]
                                      .Attachments
                                      .Request()
                                      .GetAsync();

                    string[] attachmentIds      = new string[attachments.CurrentPage.Count];
                    int      index              = 0;
                    string[] attachmentUrls     = null;
                    string[] attachmentNames    = new string[attachments.CurrentPage.Count];
                    string   attachmentLocation = null;
                    foreach (Microsoft.Graph.FileAttachment attachment in attachments.CurrentPage)
                    {
                        attachmentIds[index]     = attachment.Id;
                        attachmentNames[index++] = attachment.Name;

                        string attachmentContent = Convert.ToBase64String(attachment.ContentBytes);

                        // For files, build a stream directly from ContentBytes
                        if (attachment.Size < (4 * 1024 * 1024))
                        {
                            MemoryStream fileStream = new MemoryStream(Convert.FromBase64String(attachmentContent));

                            // OneDrive Save
                            attachmentLocation = await saveAttachmentOneDrive(accessToken, attachment.Name, fileStream, message.Subject);
                        }
                        else
                        {
                            // TODO: need to implement functionality for size > 4MB
                            return(false);
                        }
                    }

                    // TODO: Google controller goes through all attachments by itself
                    // Should probably have it same as OneDrive saving (which does each email)
                    // Need to convert one of the two..

                    /* Google Drive save start */

                    /*
                     * GoogleController google = new GoogleController();
                     * SaveAttachmentRequest newRequest = new SaveAttachmentRequest()
                     * {
                     *  filenames = attachmentNames,
                     *  attachmentIds = attachmentIds,
                     *  messageId = message.Id,
                     *  outlookRestUrl = requestUri,
                     *  outlookToken = callbackToken,
                     *  subject = message.Subject
                     * };
                     *
                     * attachmentLocation = await google.saveAttachmentGoogleDrive(newRequest);
                     *
                     * attachmentLocation = "https://drive.google.com/drive/u/1/folders/" + attachmentLocation;
                     */
                    /* Google Drive save end */



                    // Delete
                    await deleteEmailAttachments(accessToken, attachmentIds, message.Id, attachmentUrls);

                    // Patch new body to email
                    await control.updateEmailBody(requestUri, attachmentLocation, message.Id, accessToken, callbackToken);
                }
            }

            return(true);
        }
示例#15
0
        private async Task <Dictionary <Message, List <FileAttachment> > > GetFileAttachments(GraphServiceClient graphClient, IMailFolderMessagesCollectionPage messages)
        {
            var msgToAttachmentsDict = new Dictionary <Message, List <FileAttachment> >();

            for (int i = 0; i < messages.Count; i++)
            {
                if (messages[i].HasAttachments == true)
                {
                    var attachmentsList = new List <FileAttachment>();
                    IMessageAttachmentsCollectionPage attachmentsPage = await graphClient.Users["*****@*****.**"]
                                                                        .MailFolders
                                                                        [config.ArchiverId]
                                                                        .Messages[messages[i].Id]
                                                                        .Attachments
                                                                        .Request()
                                                                        .GetAsync();

                    for (int j = 0; j < attachmentsPage.Count; j++)
                    {
                        if (attachmentsPage[j].ODataType == "#microsoft.graph.fileAttachment")
                        {
                            var fileAttachment = attachmentsPage[j] as FileAttachment;
                            attachmentsList.Add(fileAttachment);
                        }
                    }
                    msgToAttachmentsDict[messages[i]] = attachmentsList;
                }
            }
            return(msgToAttachmentsDict);
        }
示例#16
0
        //public async Task<List<ContactItem>> LoadPeopleFromMeetings(DateTimeOffset date)
        //{
        //    var attendees = new List<ContactItem>();

        //    try
        //    {
        //        var meetings = await LoadMeetings(date);

        //        foreach (var m in meetings)
        //        {
        //            if (!m.IsOrganizer)
        //            {
        //                var email = (m.Organizer != null) ? m.Organizer.Address : string.Empty;
        //                var name = (m.Organizer != null) ? m.Organizer.Name : string.Empty;
        //                var c = new ContactItem(name, email, 1);

        //                attendees.Add(c);
        //            }

        //            if (m.Attendees.Count >= 0)
        //            {
        //                foreach (var a in m.Attendees)
        //                {
        //                    var c = new ContactItem("", a, 1);

        //                    attendees.Add(c);
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        Logger.WriteToLogFile(e);
        //    }

        //    return attendees;
        //}

        //internal async void LoadEvents()
        //{
        //    if (!IsInternetAvailable() || !await TrySilentAuthentication()) return;

        //    try
        //    {
        //        var token = authResult.Token;


        //        ////////////// ////////////// //////////////
        //        ////////////// Access the API
        //        ////////////// ////////////// //////////////

        //        var client = new OutlookServicesClient(new Uri(apiUrl), async () =>
        //        {
        //            // Since we have it locally from the Session, just return it here.
        //            return token;
        //        });

        // Once the token has been returned by ADAL,
        // add it to the http authorization header,
        // before making the call to access the To Do list service.
        //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);

        ///////////// QUERY 1
        //var res = await httpClient.GetAsync("https://outlook.office.com/api/v2.0/me/calendarview?startdatetime=2015-12-08T08:00:00.000Z&enddatetime=2015-12-09T08:00:00.000Z");
        //var res = await httpClient.GetAsync("https://outlook.office.com/api/v2.0/Me/Events?$top=10&$select=Subject,Start,End");
        //var text = await res.Content.ReadAsStringAsync();
        //Console.WriteLine(text);


        ///////////// QUERY 2
        //var eventResults = await client.Me.Events
        //                    .OrderByDescending(e => e.Start.DateTime)
        //                    .Take(10)
        //                    .Select(e => new DisplayEvent(e.Subject, e.Start.DateTime, e.End.DateTime, e.Attendees.Count))
        //                    .ExecuteAsync();

        // Obtain calendar event data
        //var eventsResults = await (from i in client.Me.Events where i.End >= DateTimeOffset.UtcNow select i).Take(10).ExecuteAsync();

        //Console.WriteLine(eventResults);
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e);
        //    }
        //}

        #endregion

        #region Email Queries

        /// <summary>
        /// In case the email result contains an odata count, return the value
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private static long GetResultCount(IMailFolderMessagesCollectionPage result)
        {
            return(result.AdditionalData.ContainsKey("@odata.count") ? long.Parse(result.AdditionalData["@odata.count"].ToString()) : Settings.NoValueDefault);
            // here, we could also iterate through the result and manually count (if it didn't work), but why should we when the API does it?
        }
示例#17
0
文件: MailService.cs 项目: sueely/AI
        /// <summary>
        /// Get messages in all the current user's mail folders.
        /// </summary>
        /// <param name="fromTime">search condition, start time.</param>
        /// <param name="toTime">search condition, end time.</param>
        /// <param name="getUnRead">bool flag, if get unread email.</param>
        /// <param name="isImportant">bool flag, if get important email.</param>
        /// <param name="directlyToMe">bool flag, if filter email directly to me.</param>
        /// <param name="fromAddress">search condition, filter email from this address.</param>
        /// <param name="skip">number of skipped result.</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
        public async Task <List <Message> > GetMyMessagesAsync(DateTime fromTime, DateTime toTime, bool getUnRead = false, bool isImportant = false, bool directlyToMe = false, string fromAddress = null, int skip = 0)
        {
            var optionList   = new List <QueryOption>();
            var filterString = string.Empty;

            if (getUnRead)
            {
                filterString = this.AppendFilterString(filterString, "isread:false");
            }

            if (isImportant)
            {
                filterString = this.AppendFilterString(filterString, "importance:high");
            }

            if (directlyToMe)
            {
                User me = await this._graphClient.Me.Request().GetAsync();

                var address = me.Mail ?? me.UserPrincipalName;
                filterString = this.AppendFilterString(filterString, $"to:{address}");
            }

            if (!string.IsNullOrEmpty(fromAddress))
            {
                filterString = this.AppendFilterString(filterString, $"from:{fromAddress}");
            }

            if (!string.IsNullOrEmpty(filterString))
            {
                optionList.Add(new QueryOption("$search", $"\"{filterString}\""));
            }

            // skip can't be used with search
            // optionList.Add(new QueryOption("$skip", $"{page}"));

            // some message don't have receiveddatetime. use last modified datetime.
            // optionList.Add(new QueryOption(GraphQueryConstants.Orderby, "lastModifiedDateTime desc"));
            // only get emails from Inbox folder.
            IMailFolderMessagesCollectionPage messages =
                optionList.Count != 0 ?
                await this._graphClient.Me.MailFolders.Inbox.Messages.Request(optionList).GetAsync():
                await this._graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();

            List <Message> result = new List <Message>();

            var done = false;

            while (messages?.Count > 0 && !done)
            {
                var messagesList = messages?.OrderByDescending(message => message.ReceivedDateTime).ToList();
                foreach (Message message in messagesList)
                {
                    var receivedDateTime = message.ReceivedDateTime;
                    if (receivedDateTime > fromTime && receivedDateTime < toTime)
                    {
                        if (skip > 0)
                        {
                            skip--;
                        }
                        else
                        {
                            result.Add(message);
                        }
                    }
                    else
                    {
                        done = true;
                    }

                    // make size to 5 to save memory
                    // 5 is the page size
                    if (result.Count == 5)
                    {
                        return(result.OrderByDescending(me => me.ReceivedDateTime).ToList());
                    }
                }

                if (messages.NextPageRequest != null)
                {
                    messages = await messages.NextPageRequest.GetAsync();
                }
                else
                {
                    done = true;
                }
            }

            return(result.OrderByDescending(message => message.ReceivedDateTime).ToList());
        }
示例#18
0
        private async Task CheckForUpdates()
        {
            var graphClient = GetGraphClient();

            IMailFolderMessagesCollectionPage messages = await GetUnreadMessages(graphClient);

            var msgToAttachmentsDict = await GetFileAttachments(graphClient, messages);


            foreach (KeyValuePair <Message, List <FileAttachment> > kvp in msgToAttachmentsDict)
            {
                foreach (FileAttachment attachment in kvp.Value)
                {
                    if (attachment.ContentType.Contains("image"))
                    {
                        string txtFromImg = await OCR(attachment.ContentBytes);

                        var dataName = "name:fileBlock1";
                        var msgTitle = kvp.Key.Subject;
                        //var pageTitle = String.Join(" ", txtFromImg.Split().Take(5).ToArray());
                        var htmlString =
                            "<!DOCTYPE html>" +
                            "<html>" +
                            "<head>" +
                            $"<title> {msgTitle} </title>" +
                            "</head>" +
                            "<body>";

                        htmlString += $"<p>{txtFromImg}</p>";

                        htmlString += $"<object data-attachment=\"{attachment.Name}\" data=\"{dataName}\" type=\"{attachment.ContentType}\" />";

                        htmlString += "</body>"
                                      + "</html>";
                        Console.WriteLine(htmlString);
                        await PostToNotebook(graphClient, htmlString, attachment);
                    }
                    else if (attachment.ContentType.Contains("csv"))
                    {
                        var dataName   = "name:fileBlock1";
                        var records    = CsvParse(attachment.ContentBytes);
                        var msgTitle   = kvp.Key.Subject;
                        var htmlString =
                            "<!DOCTYPE html>" +
                            "<html>" +
                            "<head>" +
                            $"<title> {msgTitle} </title>" +
                            "</head>" +
                            "<body>";
                        foreach (var record in records)
                        {
                            htmlString += $"<p>{record.Annotation} ({record.Location})</p>";
                        }
                        htmlString += $"<object data-attachment=\"{attachment.Name}\" data=\"{dataName}\" type=\"{attachment.ContentType}\" />";
                        htmlString += "</body>"
                                      + "</html>";
                        Console.WriteLine(htmlString);
                        await PostToNotebook(graphClient, htmlString, attachment);
                    }
                }
                await MarkMessageAsRead(graphClient, kvp.Key.Id);
            }

            OutputMessages(messages);
        }