예제 #1
0
        private IEnumerable <IMailFolder> GetImapSubFolders(IMailFolder folder)
        {
            try
            {
                var subfolders = folder.GetSubfolders(true, CancelToken).ToList();

                if (!subfolders.Any())
                {
                    return(subfolders);
                }

                var tempList = new List <IMailFolder>();

                foreach (var subfolder in
                         subfolders.Where(
                             f => f.Attributes.HasFlag(FolderAttributes.HasChildren)))
                {
                    tempList.AddRange(GetImapSubFolders(subfolder));
                }

                subfolders.AddRange(tempList);

                return(subfolders);
            }
            catch (Exception ex)
            {
                Log.Error("GetImapSubFolders: {0} Exception: {1}", folder.Name, ex.Message);
            }

            return(new List <IMailFolder>());
        }
예제 #2
0
        public static void RemoveFolder(IMailFolder folder, Configuration config)
        {
            using var kernel = new FakeItEasyMockingKernel();
            kernel.Rebind <ILogger>().ToConstant(Log.Logger);
            kernel.Rebind <Configuration>().ToConstant(config);
            kernel.Rebind <ImapStore>().ToSelf().InSingletonScope();
            kernel.Rebind <ImapConnectionFactory>().ToSelf().InSingletonScope();
            var imapFac = kernel.Get <ImapConnectionFactory>();

            using var connection = imapFac.GetImapConnectionAsync().Result;

            var subFolders = folder.GetSubfolders();

            foreach (var subFolder in subFolders)
            {
                RemoveFolder(subFolder, config);
            }

            folder.Open(FolderAccess.ReadWrite);
            var allMessages = folder.Search(SearchQuery.All);

            folder.SetFlags(allMessages, MessageFlags.Deleted, true);
            folder.Expunge();
            folder.Close();
            try
            {
                folder.Delete();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception while deleting folder: " + e.ToString());
            }
            connection.Disconnect(true);
        }
        public static async Task VisitChildren(ILogger logger, IMailFolder parent, Func <IMailFolder, int, int, Task <bool> >?visitor)
        {
            if (visitor == null)
            {
                return;
            }

            var subfolders            = parent.GetSubfolders().ToList();
            var subfolderCount        = subfolders.Count;
            var currentSubfolderCount = 0;

            foreach (var subfolder in subfolders)
            {
                try
                {
                    if (!await visitor(subfolder, ++currentSubfolderCount, subfolderCount))
                    {
                        return;
                    }
                } catch (Exception e) when(!(e is OperationCanceledException) && !(e is TaskCanceledException))
                {
                    logger.Error(e, "Exception while visiting child folder '{ChildName}' of parent folder '{FolderFullName}', ignoring and continuing with next child", subfolder.Name, parent.FullName);
                }
            }
        }
예제 #4
0
        public static void ListInboxFolders(EmailAccount inboxOwner, ILogger logger)
        {
            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true; // Accept all certificates
                client.Connect(inboxOwner.EmailHost, inboxOwner.ImapPort, useSsl: false);
                client.Authenticate(inboxOwner.EmailAddress, inboxOwner.EmailPassword);

                IMailFolder personal = client.GetFolder(client.PersonalNamespaces[0]);
                foreach (IMailFolder folder in personal.GetSubfolders(false))
                {
                    logger.LogInfo($"[folder] {folder.Name}");
                }

                if ((client.Capabilities & (ImapCapabilities.SpecialUse | ImapCapabilities.XList)) != 0)
                {
                    IMailFolder drafts = client.GetFolder(SpecialFolder.Sent);
                    logger.LogInfo($"[special SENT folder] {drafts.Name}");
                }
                else
                {
                    logger.LogInfo("unable to get special SENT folder");
                }

                client.Disconnect(true);
            }
        }
예제 #5
0
        public static List <IMailFolder> GettingImapSubfoldersList(Account element)
        {
            List <IMailFolder> myListFolders = new List <IMailFolder>();

            using (var client = new ImapClient())
            {
                client.Connect(element.IMAPServerDetails, element.IMAPPortDetails, SecureSocketOptions.SslOnConnect);

                client.Authenticate(element.IMAPEmailAddress, element.IMAPEmailBoxPassword);

                client.Inbox.Open(FolderAccess.ReadOnly);

                var personal = client.GetFolder(client.PersonalNamespaces[0]);

                IMailFolder CompleteFolder = personal.GetSubfolders()[1];

                foreach (var folder in CompleteFolder.GetSubfolders())
                {
                    myListFolders.Add(folder);
                }

                client.Disconnect(true);
            }
            return(myListFolders);
        }
예제 #6
0
        private IEnumerable <IMailFolder> Folders(IMailFolder rootFolder, bool recursive, ImapClient client)
        {
            if (client == null)
            {
                client = new ImapClient();
                Connect(client);
            }

            IMailFolder parentFolder = rootFolder ?? client.GetFolder(client.PersonalNamespaces[0]);

            foreach (var folder in parentFolder.GetSubfolders(false))
            {
                logger.LogTrace($"return folder: {folder.FullName}");
                yield return(folder);

                if (recursive)
                {
                    var internalFolders = Folders(folder, recursive, client);
                    foreach (var internalFolder in internalFolders)
                    {
                        logger.LogTrace($"return folder: {internalFolder.FullName}");
                        yield return(internalFolder);
                    }
                }
            }
        }
예제 #7
0
        public void ChildFolders()
        {
            using (var client = new ImapClient())
            {
                //authenticate
                client.ServerCertificateValidationCallback = (s, c, ch, e) => true;
                client.Connect(Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
                client.AuthenticationMechanisms.Remove(Constant.GoogleOAuth);
                client.Authenticate(Constant.GoogleUserName, Constant.GenericPassword);

                client.Inbox.Open(FolderAccess.ReadWrite);

                IMailFolder personal = client.GetFolder("EnrollmentStudentServicesA&FBursarPropel");

                foreach (IMailFolder folder in personal.GetSubfolders())
                {
                    Console.WriteLine(folder.Name);

                    IEnumerable <IMailFolder> collection = folder.GetSubfolders();

                    foreach (var n in collection)
                    {
                        Console.WriteLine(n.Name);
                    }
                }

                client.Disconnect(true);
            }
        }
예제 #8
0
 int TraverseFolder(IMailFolder mailFolder)
 {
     return(attachmentProcessor.TryVisitFolder(mailFolder, (processed, requireAttention) => {}) +
            mailFolder
            .GetSubfolders(subscribedOnly: false)
            .Select(subFolder => TraverseFolder(subFolder))
            .Sum());
 }
예제 #9
0
        public static void ListSubfolders(IMailFolder folder)
        {
            Console.WriteLine("[folder] {0}", folder.Name);

            foreach (var f in folder.GetSubfolders(false))
            {
                ListSubfolders(f);
            }
        }
예제 #10
0
        /// <summary>
        /// Get all folders in client recursively
        /// </summary>
        private List <IMailFolder> RecursiveGetFolder(IMailFolder folder)
        {
            var folders = new List <IMailFolder>();

            foreach (var f in folder.GetSubfolders())
            {
                folders.Add(f);
                folders.AddRange(RecursiveGetFolder(f));
            }
            return(folders);
        }
예제 #11
0
        private static void OutputFolder(OutputTable output, IMailFolder folder, ref int messages, ref int unread, int indent = 0)
        {
            var a = folder.Open(FolderAccess.ReadOnly);

            output.AddRow("".PadRight(indent) + folder.Name, folder.Count, folder.Unread);
            var q = folder.GetQuota();

            messages += folder.Count;
            unread   += folder.Unread;

            folder.Close();

            foreach (var subFolder in folder.GetSubfolders())
            {
                OutputFolder(output, subFolder, ref messages, ref unread, indent + 1);
            }
        }
예제 #12
0
        private static IMailFolder GetFolder(IMailFolder parent, Queue <string> names)
        {
            var name = names.Dequeue();

            var folder = parent.GetSubfolders().FirstOrDefault(f => f.Name == name);

            if (folder == null)
            {
                folder = parent.Create(name, true);
            }

            if (names.Count == 0)
            {
                return(folder);
            }
            else
            {
                return(GetFolder(folder, names));
            }
        }
        public static IMailFolder FindFolder(IMailFolder toplevel, string name)
        {
            var subfolders = toplevel.GetSubfolders().ToList();

            foreach (var subfolder in subfolders)
            {
                if (subfolder.Name == name)
                {
                    return(subfolder);
                }
            }

            foreach (var subfolder in subfolders)
            {
                var folder = FindFolder(subfolder, name);

                if (folder != null)
                {
                    return(folder);
                }
            }

            return(null);
        }
예제 #14
0
        private IEnumerable <IMailFolder> GetImapSubFolders(IMailFolder folder)
        {
            try
            {
                var subfolders = folder.GetSubfolders(true, CancelToken).ToList();

                if (!subfolders.Any())
                {
                    return(subfolders);
                }

                var tempList = new List <IMailFolder>();

                foreach (var subfolder in subfolders)
                {
                    try
                    {
                        tempList.AddRange(GetImapSubFolders(subfolder));
                    }
                    catch
                    {
                        //Skip
                    }
                }

                subfolders.AddRange(tempList);

                return(subfolders);
            }
            catch
            {
                //Skip
            }

            return(new List <IMailFolder>());
        }
        /// <summary>
        /// Rally is authenticated in the constructor
        /// </summary>
        /// <param name="workspace"></param>

        public void SyncThroughLabels(string workspace)
        {
            #region variables
            SlackClient       _slackClient = new SlackClient(SLACK.SlackApiToken, 100);
            DynamicJsonObject toCreate     = new DynamicJsonObject();
            toCreate[RALLY.WorkSpace] = workspace;
            DynamicJsonObject           attachmentContent   = new DynamicJsonObject();
            DynamicJsonObject           attachmentContainer = new DynamicJsonObject();
            CreateResult                createUserStory;
            CreateResult                attachmentContentCreateResult;
            CreateResult                attachmentContainerCreateResult;
            string[]                    allAttachments;
            Dictionary <string, string> attachmentsDictionary = new Dictionary <string, string>();
            string userStorySubject;
            string userStoryDescription;
            string userStoryReference;
            string attachmentReference;
            int    anotherOne = 0;
            string base64String;
            string attachmentFileName;
            string fileName;
            string _objectId;
            string _userStoryUrl;
            string _slackAttachmentString;
            string slackChannel;
            #endregion

            using (ImapClient client = new ImapClient())
            {
                AuthenticateWithGoogleImap(client);

                client.Inbox.Open(FolderAccess.ReadWrite);
                IMailFolder parentFolder    = client.GetFolder(EMAIL.EnrollmentStudentServicesFolder);
                IMailFolder processedFolder = parentFolder.GetSubfolder(RALLYQUERY.ProcessedEnrollmentStudentServices);

                foreach (IMailFolder childFolder in parentFolder.GetSubfolders())
                {
                    #region Folders
                    if (childFolder.Name.Equals(RALLYQUERY.GmailFolderCatalyst2016))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectCatalyst2016;
                        slackChannel            = SLACK.Channelcatalyst2016;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderHonorsEnhancements))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectHonorsEnhancements;
                        slackChannel            = SLACK.ChannelHonorsEnhancements;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderPalHelp))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectPalHelp;
                        slackChannel            = SLACK.ChannelPalHelp;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderPciAzureTouchNetImplementation))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectPciAzureTouchNetImplementation;
                        slackChannel            = SLACK.ChannelAzureTouchNet;
                    }
                    else
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectScrumptious;
                        slackChannel            = SLACK.ChannelScrumptious;
                    }
                    #endregion

                    Console.WriteLine(childFolder.Name);
                    childFolder.Open(FolderAccess.ReadWrite);
                    IList <UniqueId> childFolderMsgUniqueIds = childFolder.Search(SearchQuery.NotSeen);

                    if (childFolderMsgUniqueIds.Any())
                    {
                        foreach (UniqueId uid in childFolderMsgUniqueIds)
                        {
                            MimeMessage message = childFolder.GetMessage(uid);
                            userStorySubject     = message.Subject;
                            userStoryDescription =
                                "From: " + message.From +
                                "<br>" + "Date Sent: " + message.Date + "</br>" +
                                "<br>" + "Subject: " + userStorySubject + "</br>" +
                                "<br>" + "Request: " + message.GetTextBody(TextFormat.Plain) + "<br>";

                            if (userStorySubject.IsEmpty())
                            {
                                userStorySubject = "<No Subject User Story>";
                            }

                            toCreate[RALLY.Name]        = userStorySubject;
                            toCreate[RALLY.Description] = userStoryDescription;
                            createUserStory             = _rallyRestApi.Create(RALLY.HierarchicalRequirement, toCreate);
                            userStoryReference          = createUserStory.Reference;

                            #region Download Attachments

                            foreach (MimeEntity attachment in message.BodyParts)
                            {
                                string attachmentFile = attachment.ContentDisposition?.FileName ??
                                                        attachment.ContentType.Name;
                                string attachmentFilePath = Concat(STORAGE.MimeKitAttachmentsDirectoryWork,
                                                                   Path.GetFileName(attachmentFile));

                                if (!IsNullOrWhiteSpace(attachmentFile))
                                {
                                    if (File.Exists(attachmentFilePath))
                                    {
                                        string extension = Path.GetExtension(attachmentFilePath);
                                        string fileNameWithoutExtension =
                                            Path.GetFileNameWithoutExtension(attachmentFilePath);
                                        attachmentFile = Format(fileNameWithoutExtension + "-{0}" + "{1}", ++anotherOne,
                                                                extension);
                                        attachmentFilePath =
                                            Path.Combine(STORAGE.MimeKitAttachmentsDirectoryWork, attachmentFile);
                                    }

                                    using (var attachmentStream = File.Create(attachmentFilePath))
                                    {
                                        MimeKit.MimePart part = (MimeKit.MimePart)attachment;
                                        part.ContentObject.DecodeTo(attachmentStream);
                                    }

                                    Console.WriteLine("Downloaded: " + attachmentFile);
                                }
                            }

                            #endregion

                            #region Process Attachments

                            allAttachments = Directory.GetFiles(STORAGE.MimeKitAttachmentsDirectoryWork);
                            foreach (string file in allAttachments)
                            {
                                base64String       = FileToBase64(file);
                                attachmentFileName = Path.GetFileName(file);
                                fileName           = Empty;

                                if (!(attachmentsDictionary.TryGetValue(base64String, out fileName)))
                                {
                                    Console.WriteLine("Added to Dictionary: " + file);
                                    attachmentsDictionary.Add(base64String, attachmentFileName);
                                }

                                File.Delete(file);
                            }

                            #endregion

                            #region Upload to Rally
                            foreach (KeyValuePair <string, string> attachmentPair in attachmentsDictionary)
                            {
                                try
                                {
                                    //create attachment content
                                    attachmentContent[RALLY.Content] = attachmentPair.Key;
                                    attachmentContentCreateResult    = _rallyRestApi.Create(
                                        RALLY.AttachmentContent,
                                        attachmentContent);
                                    attachmentReference = attachmentContentCreateResult.Reference;

                                    //create attachment contianer
                                    attachmentContainer[RALLY.Artifact]    = userStoryReference;
                                    attachmentContainer[RALLY.Content]     = attachmentReference;
                                    attachmentContainer[RALLY.Name]        = attachmentPair.Value;
                                    attachmentContainer[RALLY.Description] = RALLY.EmailAttachment;
                                    attachmentContainer[RALLY.ContentType] = "file/";

                                    //Create & associate the attachment
                                    attachmentContainerCreateResult = _rallyRestApi.Create(RALLY.Attachment,
                                                                                           attachmentContainer);
                                    Console.WriteLine("Uploaded to Rally: " + attachmentPair.Value);
                                }
                                catch (WebException e)
                                {
                                    Console.WriteLine("Attachment: " + e.Message);
                                }
                            }
                            attachmentsDictionary.Clear();

                            #endregion

                            #region See and Move

                            childFolder.SetFlags(uid, MessageFlags.Seen, true);
                            childFolder.MoveTo(uid, processedFolder);

                            #endregion

                            #region Slack

                            if (userStoryReference != null)
                            {
                                _objectId              = Ref.GetOidFromRef(userStoryReference);
                                _userStoryUrl          = string.Concat(SLACK.UserStoryUrlFormat, _objectId);
                                _slackAttachmentString = string.Format("User Story: <{0} | {1} >", _userStoryUrl, message.Subject);

                                SlackMessage slackMessage = new SlackMessage
                                {
                                    //Channel is set according to the source of the email message folder
                                    Channel   = slackChannel,
                                    Text      = SLACK.SlackNotificationBanner,
                                    IconEmoji = Emoji.SmallRedTriangle,
                                    Username  = SLACK.SlackUser
                                };

                                SlackAttachment slackAttachment = new SlackAttachment
                                {
                                    Fallback = _slackAttachmentString,
                                    Text     = _slackAttachmentString,
                                    Color    = SLACK.HexColor
                                };

                                slackMessage.Attachments = new List <SlackAttachment> {
                                    slackAttachment
                                };
                                _slackClient.Post(slackMessage);
                            }
                            else
                            {
                                throw new NullReferenceException();
                            }

                            #endregion

                            #region Email
                            using (SmtpClient smtpClient = new SmtpClient())
                            {
                                if (!smtpClient.IsAuthenticated)
                                {
                                    AuthenticateWithGoogleSmtp(smtpClient);
                                }

                                //iterate throught the email addresses, to send the emails
                                List <MailboxAddress> emailNoticationList = new List <MailboxAddress>();
                                emailNoticationList.Add(new MailboxAddress("*****@*****.**"));

                                foreach (var mailboxAddress in emailNoticationList)
                                {
                                    MimeMessage emailNotificationMessage = new MimeMessage();
                                    emailNotificationMessage.From.Add(new MailboxAddress("Rally Integration", EMAIL.GoogleUsername));
                                    emailNotificationMessage.To.Add(mailboxAddress);
                                    emailNotificationMessage.Subject = "Rally Notification: " + userStorySubject;
                                    emailNotificationMessage.Body    = new TextPart("plain")
                                    {
                                        Text = "User Story: " + _userStoryUrl
                                    };

                                    smtpClient.Send(emailNotificationMessage);
                                }

                                //disconnect here...
                                //this will make the program connect and disconnect in a loop
                            }
                            #endregion

                            Console.WriteLine(message.Subject + " Created");
                        }
                    }
                    else
                    {
                        Console.WriteLine(childFolder + "-No Unread Messages");
                    }
                }
                Console.WriteLine("Done");
                client.Disconnect(true);
            }
        }
예제 #16
0
        void LoadChildFolders(IMailFolder folder)
        {
            var children = folder.GetSubfolders();

            LoadChildFolders(folder, children);
        }
        private IList <UniqueId> ListUid(IMailFolder mailFolder)
        {
            mailFolder.Open(FolderAccess.ReadOnly);
            IList <UniqueId> list = mailFolder.Search(SearchQuery.All);

            Console.WriteLine("Folder{0} ", mailFolder.Name);

            foreach (UniqueId item2 in list)
            {
                try
                {
                    MimeMessage message = mailFolder.GetMessage(item2);

                    foreach (var attachment in message.Attachments)
                    {
                        if (attachment is MessagePart)
                        {
                            var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
                            var rfc822   = (MessagePart)attachment;
                            rfc822.Message.WriteTo(Path.Combine(this._pathinit, fileName));
                            attach.file   = fileName;
                            attach.source = Path.Combine(this._pathinit, fileName);
                            attach.CheckPath();
                            attach.Move();
                        }
                        else
                        {
                            var part     = (MimePart)attachment;
                            var fileName = part.FileName;

                            using (var stream = File.Create(Path.Combine(this._pathinit, fileName)))
                            {
                                part.Content.DecodeTo(stream);
                            }
                            attach.file   = fileName;
                            attach.source = Path.Combine(this._pathinit, fileName);
                            attach.CheckPath();
                            attach.Move();
                        }
                    }

                    var getChilds = mailFolder.GetSubfolders(StatusItems.None, false);
                    if (getChilds.Count() > 0)
                    {
                        foreach (var item in getChilds)
                        {
                            if (item.Name == ".before attachs" || item.Name == ".before heart")
                            {
                                continue;
                            }
                            else
                            {
                                this.ListUid(item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }



            return(list);
        }
예제 #18
0
        protected IEnumerable<IMailFolder> GetMoreFolders(IMailFolder folder)
        {
            var results = new List<IMailFolder>();

            foreach (var f in folder.GetSubfolders())
            {
                results.Add(f);

                if (f.Attributes.HasFlag(FolderAttributes.HasChildren))
                {
                    results.AddRange(GetMoreFolders(f));
                }
            }

            return results;
        }
예제 #19
0
        //---------------------IMAP------MailKit-------------------------------


        public static async Task <List <MessageParts> > CustomsDownloadBodyPartsAsync(Account element, string FolderName, BinarySearchQuery queryCustom)
        {
            List <MessageParts> MessagesListRender = new List <MessageParts>();
            List <IMailFolder>  myListFolders      = new List <IMailFolder>();

            using (var client = new ImapClient())
            {
                await client.ConnectAsync(element.IMAPServerDetails, element.IMAPPortDetails, SecureSocketOptions.SslOnConnect);

                await client.AuthenticateAsync(element.IMAPEmailAddress, element.IMAPEmailBoxPassword);

                await client.Inbox.OpenAsync(FolderAccess.ReadOnly);

                var personal = client.GetFolder(client.PersonalNamespaces[0]);

                IMailFolder CompleteFolder = personal.GetSubfolders()[1];

                foreach (var folder in CompleteFolder.GetSubfolders())
                {
                    myListFolders.Add(folder);
                }

                int indexOfFolder = myListFolders.FindIndex(a => a.Name == FolderName);
                if (indexOfFolder > 0)
                {
                    await myListFolders[indexOfFolder].OpenAsync(FolderAccess.ReadOnly);

                    if (queryCustom == null)
                    {
                        DateTime DateNow = new DateTime();
                        DateNow = DateTime.Now;
                        var query = SearchQuery.DeliveredAfter(new DateTime(2019, 05, 01)).And(SearchQuery.DeliveredBefore(DateNow));
                        var uids  = await myListFolders[indexOfFolder].SearchAsync(query);
                        const MessageSummaryItems SummaryItems = MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope | MessageSummaryItems.Flags | MessageSummaryItems.BodyStructure;
                        var timeout = new CancellationToken();
                        MessagesList = await myListFolders[indexOfFolder].FetchAsync(uids, SummaryItems, timeout);
                    }
                    if (queryCustom != null)
                    {
                        var uids = myListFolders[indexOfFolder].Search(queryCustom);
                        const MessageSummaryItems SummaryItems = MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope | MessageSummaryItems.Flags | MessageSummaryItems.BodyStructure;
                        var timeout = new CancellationToken();
                        MessagesList = await myListFolders[indexOfFolder].FetchAsync(uids, SummaryItems, timeout);
                    }

                    foreach (var message in MessagesList)
                    {
                        MessageParts temp = new MessageParts();
                        temp.Uid = message.UniqueId.ToString();

                        var bodyPart = message.TextBody;
                        var body     = (TextPart)myListFolders[indexOfFolder].GetBodyPart(message.UniqueId, bodyPart);
                        temp.Body = body.Text;

                        string str   = message.Envelope.Date.ToString();
                        int    index = str.IndexOf("+") > 0 ? str.IndexOf("+") : str.IndexOf("-");
                        temp.Date = str.Substring(0, index);

                        temp.From    = message.Envelope.From.ToString();
                        temp.Cc      = message.Envelope.Cc.ToString();
                        temp.Subject = message.Envelope.Subject.ToString();
                        temp.To      = message.Envelope.To.ToString();
                        MessagesListRender.Add(temp);
                    }
                }
                client.Disconnect(true);
            }
            return(MessagesListRender);
        }
예제 #20
0
        public void IterateThroughEmail()
        {
            int anotherOne = 0;

            using (var client = new ImapClient())
            {
                //authenticate
                client.ServerCertificateValidationCallback = (s, c, ch, e) => true;
                client.Connect(Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
                client.AuthenticationMechanisms.Remove(Constant.GoogleOAuth);
                client.Authenticate(Constant.GoogleUserName, Constant.GenericPassword);

                client.Inbox.Open(FolderAccess.ReadWrite);

                //IMailFolder personal = client.GetFolder(client.PersonalNamespaces[0]);

                IMailFolder personal = client.GetFolder(Constant.EnrollmentStudentServicesFolder);
                foreach (IMailFolder folder in personal.GetSubfolders())
                {
                    Console.WriteLine(folder.Name);
                    //give each folder read and write access
                    folder.Open(FolderAccess.ReadWrite);
                    //uids in the specific folder
                    IList <UniqueId> uids = folder.Search(SearchQuery.All);
                    foreach (var x in uids)
                    {
                        //in folder A
                        MimeMessage message = folder.GetMessage(x);
                        string      subject = message.Subject;
                        string      body    = message.TextBody;
                        Console.WriteLine(subject + "\n" + body);

                        foreach (MimeEntity attachment in message.BodyParts)
                        {
                            string fileName     = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
                            string anAttachment = string.Concat(Constant.MimeKitAttachmentsDirectoryWork, fileName);

                            if (!string.IsNullOrWhiteSpace(fileName))
                            {
                                if (File.Exists(anAttachment))
                                {
                                    string extension = Path.GetExtension(anAttachment);
                                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(anAttachment);
                                    fileName = string.Format(fileNameWithoutExtension + "-{0}" + "{1}", ++anotherOne,
                                                             extension);
                                    anAttachment = string.Concat(Constant.MimeKitAttachmentsDirectoryWork, fileName);
                                }

                                using (FileStream attachmentStream = File.Create(anAttachment))
                                {
                                    MimeKit.MimePart part = (MimeKit.MimePart)attachment;
                                    part.ContentObject.DecodeTo(attachmentStream);
                                }

                                Console.WriteLine("Downloaded: " + fileName);
                            }
                        }
                    }
                }
                client.Disconnect(true);
            }
        }