コード例 #1
0
        public IEnumerable <MailMessagePreviewDTO> GetMailInbox()
        {
            List <MailMessagePreviewDTO> list = new List <MailMessagePreviewDTO>();

            using (ImapClient client = new ImapClient())
            {
                // For demo-purposes, accept all SSL certificates
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("imap.gmail.com", 993, true);

                client.Authenticate("*****@*****.**", "V3@pu166@@!!");

                // The Inbox folder is always available on all IMAP servers...
                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);
                int index = Math.Max(inbox.Count - 10, 0);
                IList <IMessageSummary> items = inbox.Fetch(index, -1, MessageSummaryItems.UniqueId);

                foreach (IMessageSummary item in items)
                {
                    MimeKit.MimeMessage message = inbox.GetMessage(item.UniqueId);
                    list.Add(new MailMessagePreviewDTO
                    {
                        Date    = message.Date.DateTime.ToUniversalTime(),
                        Sender  = message.From[0].Name,
                        Subject = message.Subject
                    });
                }
            }
            return(list);
        }
コード例 #2
0
 public Folder(IMailFolder imapFolder)
 {
     _imapFolder = imapFolder;
     _imapFolder.Open(FolderAccess.ReadOnly);
     NumberOfMessages = _imapFolder.Count;
     _imapFolder.Close();
 }
コード例 #3
0
ファイル: MailFetchTask.cs プロジェクト: feyris-tan/azusa
        public void CopyFolder(IMailFolder folder, Folder sqlEntity, bool update, string password)
        {
            try
            {
                folder.Open(FolderAccess.ReadOnly);
            }
            catch (Exception)
            {
                return;
            }

            Random           rng   = AzusaContext.GetInstance().RandomNumberGenerator;
            IList <UniqueId> uuids = folder.Search(FolderService.GetSearchQuery(sqlEntity));

            foreach (UniqueId uuid in uuids)
            {
                if (MessageService.TestForMessage((int)uuid.Id))
                {
                    continue;
                }

                var message = folder.GetMessage(uuid);

                byte[] saltBuffer = new byte[16];
                rng.NextBytes(saltBuffer);
                Array.Copy(azusaString, 0, saltBuffer, 0, azusaString.Length);
                int iterations = rng.Next(1000, short.MaxValue);
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, saltBuffer, iterations);
                Aes aes = Aes.Create();
                aes.Key = deriveBytes.GetBytes(32);
                aes.IV  = deriveBytes.GetBytes(16);
                MemoryStream ms           = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
                message.WriteTo(cryptoStream);
                cryptoStream.Flush();

                Mail child = new Mail();
                child.Uid          = (int)uuid.Id;
                child.MessageUtime = message.Date.DateTime.ToUnixTime();
                child.Folder       = sqlEntity.id;
                child.From         = message.From[0].ToString();
                if (message.To.Count > 0)
                {
                    child.To = message.To[0].ToString();
                }
                else
                {
                    child.To = null;
                }
                child.Subject    = message.Subject;
                child.Salt       = saltBuffer;
                child.Iterations = (short)iterations;
                child.Data       = new byte[ms.Position];
                Array.Copy(ms.GetBuffer(), 0, child.Data, 0, ms.Position);

                MessageService.StoreMessage(child);
            }

            folder.Close(false);
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: ford153focus/mailfilter
        private static void ProcessMailbox(dynamic mailbox)
        {
            ConsoleUtils.WriteWarning(mailbox["login"]);

            // For demo-purposes, accept all SSL certificates
            var client = new ImapClient {
                ServerCertificateValidationCallback = (s, c, h, e) => true
            };

            client.Connect(mailbox["host"], mailbox["port"], true);

            client.Authenticate(mailbox["login"], mailbox["password"]);

            // The Inbox folder is always available on all IMAP servers...
            IMailFolder inbox = client.Inbox;

            inbox.Open(FolderAccess.ReadWrite);

            // convert filters: from JsonArray to List of strings
            var filters = new List <string>();

            foreach (dynamic filter in mailbox["applicable_filters"])
            {
                filters.Add(filter.ToString().Trim('"'));
            }

            for (var i = 0; i < inbox.Count; i++)
            {
                var wrappedMessage = new WrappedMessage(client, inbox, i, filters);
                ProcessMessage(wrappedMessage);
            }

            client.Disconnect(true);
        }
コード例 #5
0
        private async void Update()
        {
            IMailFolder inbo = await Task.Run(() => EmailAsync(login, pass));

            lbMail.Content = tbLogin.Text;

            inbo.Open(FolderAccess.ReadOnly);
            progress.Maximum        = inbo.Count;
            lbMail.Content          = login;
            spLog.Visibility        = Visibility.Collapsed;
            gridMainPage.Visibility = Visibility.Visible;

            try
            {
                for (int i = inbo.Count - 1; i >= 0; i--)
                {
                    var message = await inbo.GetMessageAsync(i);

                    letters.Add(new Letter
                    {
                        Sender  = message.From.Mailboxes.First().Name,
                        Date    = message.Date.DateTime.ToString(),
                        Subject = message.Subject,
                        Text    = message.TextBody
                    }
                                );
                    progress.Value++;
                }
            }
            catch { }
            await imap.DisconnectAsync(true);
        }
コード例 #6
0
        public virtual async Task <int> GetTotalMailCount()
        {
            _mailFolder = await AuthenticateAsync();

            _mailFolder.Open(FolderAccess.ReadOnly);
            return((await _mailFolder.SearchAsync(SearchQuery.All))?.Count ?? 0);
        }
コード例 #7
0
        private int VisitFolder(IMailFolder folder,
                                Action <List <UniqueId>, List <UniqueId> > onCompletion)
        {
            folder.Open(FolderAccess.ReadOnly);

            var summaries = fetch(folder).ToArray();

            var processed = summaries
                            .Where(summary => saveEmailAttachments(folder, summary)
                                   .Equals(SaveResult.Ok)
                                   )
                            .ToArray();

            var requireAttention = summaries
                                   .Except(processed)
                                   .ToArray();

            Console.WriteLine("{0} emails were successfully processed", processed.Length);
            Console.WriteLine("{0} emails require attention", requireAttention.Length);

            onCompletion(
                processed.Select(summary => summary.UniqueId).ToList(),
                requireAttention.Select(summary => summary.UniqueId).ToList()
                );

            return(processed.Count());
        }
コード例 #8
0
ファイル: PopHelper.cs プロジェクト: zzxulong/study
 /// <summary>
 /// 邮件添加标识(已读,已回复,已删除等等).参数值参考EmailViewM实体同名属性
 /// 调用前先调用配置方法CfgIMAP()
 /// </summary>
 /// <param name="uniqueIdls">同一文件夹下的邮件唯一标识列表</param>
 /// <param name="flag">标识代码 1=已读 2=已回复 8=删除</param>
 /// <param name="folderType">文件夹名</param>
 public void SetFlag(List <uint> uniqueIdls, int flag, string folderType = null)
 {
     try
     {
         using (ImapClient client = ConnectIMAP())
         {
             List <UniqueId> uniqueids    = uniqueIdls.Select(o => new UniqueId(o)).ToList();
             MessageFlags    messageFlags = (MessageFlags)flag;
             if (folderType == null)
             {
                 folderType = client.Inbox.Name;
             }
             IMailFolder folder = client.GetFolder(folderType);
             folder.Open(FolderAccess.ReadWrite);
             folder.AddFlags(uniqueids, messageFlags, true);
             //
             folder.Close();
             client.Disconnect(true);
         }
     }
     catch (Exception e)
     {
         ErrMsg = $"邮件添加标识时异常:{e.ToString()} [{e.Message}]";
     }
 }
コード例 #9
0
ファイル: PopHelper.cs プロジェクト: zzxulong/study
        /// <summary>
        /// 将邮件保存到草稿箱 返回邮件的唯一标识
        /// 调用前先调用配置方法CfgIMAP(),调用制做邮件方法
        /// </summary>
        public int SaveDrafts(int uniqueId = -1)
        {
            try
            {
                using (ImapClient client = ConnectIMAP())
                {
                    // 打开草稿箱,添加邮件
                    IMailFolder folder = client.GetFolder(SpecialFolder.Drafts);
                    folder.Open(FolderAccess.ReadWrite);

                    // 如果保存的是已经有的草稿邮件,则删除它再保存新的草稿.(没找到保存已有草稿的办法)
                    if (uniqueId > -1)
                    {
                        List <UniqueId> uidls = new List <UniqueId>();
                        uidls.Add(new UniqueId((uint)uniqueId));
                        folder.SetFlags(uidls, MessageFlags.Seen | MessageFlags.Deleted, true);
                        folder.Expunge(uidls);
                    }

                    UniqueId?uid = folder.Append(this.message, MessageFlags.Seen | MessageFlags.Draft);
                    //
                    folder.Close();
                    client.Disconnect(true);
                    return(uid.HasValue ? (int)uid.Value.Id : -1);
                }
            }
            catch (Exception e)
            {
                ErrMsg = $"邮件保存草稿时异常:{e.ToString()} [{e.Message}]";
                return(-1);
            }
        }
コード例 #10
0
ファイル: PopHelper.cs プロジェクト: zzxulong/study
 /// <summary>
 /// 根据唯一标识和文件夹名,获取单个邮件
 /// </summary>
 /// <param name="folderName"></param>
 /// <returns></returns>
 public EmailViewM GetEmailByUid(uint uniqueid, string folderName = null)
 {
     try
     {
         using (ImapClient client = ConnectIMAP())
         {
             if (folderName == null)
             {
                 folderName = client.Inbox.Name;
             }
             IMailFolder folder = client.GetFolder(folderName);
             folder.Open(FolderAccess.ReadOnly);
             var email  = folder.GetMessage(new UniqueId(uniqueid));
             var entity = FillEntity(null, email);
             //
             folder.Close();
             client.Disconnect(true);
             //
             return(entity);
         }
     }
     catch (Exception e)
     {
         ErrMsg = $"获取单个邮件异常:{e.ToString()} [{e.Message}]";
         return(null);
     }
 }
コード例 #11
0
ファイル: MailService.cs プロジェクト: WailGree/remailcore
        public List <Email> GetMails(string username, string password, bool checkBackup = false)
        {
            _emails = new List <Email>();
            if (CheckInternet())
            {
                using (var client = new ImapClient())
                {
                    client.Connect("imap.gmail.com", 993, true);
                    client.Authenticate(username, password);
                    //The Inbox folder is always available on all IMAP servers...
                    IMailFolder inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly);

                    AddEmailsToList(client);

                    client.Disconnect(true);
                    if (checkBackup)
                    {
                        NewBackup(_emails);
                    }
                }
            }
            else
            {
                if (checkBackup)
                {
                    _emails = LoadBackup();
                }
            }

            _emails.Reverse();
            return(_emails);
        }
コード例 #12
0
        public IEnumerable <IEMailMessageI> GetReadMailMessages(IMailRequestI mailRequest)
        {
            var mailMessages = new List <IEMailMessageI>();

            using (ImapClient client = new ImapClient())
            {
                client.Connect(MailReadersSettingsModule.Settings.IMAP, MailReadersSettingsModule.Settings.IMAPport, SecureSocketOptions.SslOnConnect);
                client.Authenticate(MailReadersSettingsModule.Settings.Login, MailReadersSettingsModule.Settings.Password);
                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);
                var uids = inbox.Search(SearchQuery.Seen);
                foreach (var item in uids)
                {
                    var message     = inbox.GetMessage(item);
                    var mailMessage = EntityManager <IEMailMessageI> .Instance.Create();

                    mailMessage.Name                 = DateTime.Now.ToString();
                    mailMessage.CreationDate         = DateTime.Now;
                    mailMessage.Tema                 = message.Subject;
                    mailMessage.Soobschenie          = message.HtmlBody;
                    mailMessage.DataPolucheniePisjma = message.Date.UtcDateTime;
                    mailMessage.OtKogo               = message.From.FirstOrDefault().Name;
                    mailMessage.Save();
                    mailMessages.Add(mailMessage);
                }
            }
            return(mailMessages.AsEnumerable());
        }
コード例 #13
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);
        }
コード例 #14
0
ファイル: Provider.cs プロジェクト: Matioz/JanuszMail
        public IList <Tuple <string, string> > GetBasicInfo(string folder, int page, int pageSize)
        {
            List <Tuple <string, string> > Info = new List <Tuple <string, string> >();

            if (!IsAuthenticated())
            {
                return(Info);
            }
            IMailFolder mailFolder = GetFolder(folder);

            mailFolder.Open(FolderAccess.ReadWrite);
            var Items = mailFolder.Fetch((page - 1) * pageSize, pageSize, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags | MessageSummaryItems.All);

            if (Items == null)
            {
                Items = new List <IMessageSummary>();
            }
            foreach (var mail in (Items as List <MessageSummary>))
            {
                Info.Add(new Tuple <string, string>(mail.NormalizedSubject, mail.Envelope.From[0].Name));
            }

            mailFolder.Close();
            return(Info);
        }
コード例 #15
0
        public async Task <UniqueId?> WriteAndUnlockStore(IMailFolder parentFolder, EmailBackedKeyValueStore?kvStore, LockResult activeLock)
        {
            if (kvStore == null)
            {
                return(UniqueId.Invalid);
            }

            try
            {
                UniqueId?replacementResult = null;
                // TBD review locking
                lock (parentFolder.SyncRoot)
                {
                    parentFolder.Open(FolderAccess.ReadWrite);
                    logger.Debug("Updating existing storage message in folder {FolderPath} with ID {@ID}", parentFolder.FullName, kvStore.MessageAndId.UniqueId);
                    replacementResult = parentFolder.Replace(kvStore.MessageAndId.UniqueId, kvStore.MessageAndId.Message);
                    parentFolder.SetFlags(kvStore.MessageAndId.UniqueId, MessageFlags.Seen, true);
                }
                return(replacementResult);
            }
            finally
            {
                var unlockResult = await remoteLock.ReleaseLock(parentFolder, activeLock.LockResourceName, activeLock.ResultingLockCookie);

                if (!unlockResult)
                {
                    logger.Warning("Could not unlock the following lock: {@LockResult}", activeLock);
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Reads all the messages.
        /// </summary>
        private static void ReadMessage()
        {
            using (ImapClient client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect("imap.gmail.com", 993, true);
                client.Authenticate(from.Address, password);

                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

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

                for (int i = 0; i < inbox.Count; i++)
                {
                    MimeMessage message = inbox.GetMessage(i);
                    Console.WriteLine("\n-------------------- messsage " + i + 1 + ", size=" + inbox.Fetch(0, -1, MessageSummaryItems.Size).ElementAt(i).Size + " --------------------");
                    Console.WriteLine("From: {0}", message.From[0]);
                    Console.WriteLine("Subject: {0}", message.Subject);
                    Console.WriteLine("Text: {0}", message.TextBody);
                    Console.WriteLine("-------------------- end of message " + i + 1 + " --------------------");
                }

                Console.WriteLine("Press a key to continue");
                Console.ReadKey();
                client.Disconnect(true);
            }
        }
コード例 #17
0
        private async Task CheckMailfolder(IMailFolder mailFolder)
        {
            if (!mailFolder.IsOpen)
            {
                mailFolder.Open(FolderAccess.ReadOnly);
            }

            var folderStatus = GetFolderStatus(mailFolder.FullName);

            var ids = await SearchMail(mailFolder, folderStatus);


            var newIds = ids
                         .Where(id => id > folderStatus.LastReceived)
                         .ToList();

            foreach (var uid in newIds)
            {
                var message = await GetMessage(mailFolder, uid);

                folderStatus.LastReceived = uid;

                ReportMessage(message);
            }

            folderStatus.LastChecked = DateTime.Now;
        }
コード例 #18
0
ファイル: MailList.cs プロジェクト: delavet/HelperUWP
        private async Task <List <MailSummary> > executeLoadMore()
        {
            try
            {
                folder.Open(FolderAccess.ReadOnly);
                int lowBound, highBound;
                highBound = folder.Count - 20 * current_page - 1;
                lowBound  = highBound - 19;
                if (lowBound <= 0)
                {
                    lowBound = 0;
                }
                List <MailSummary> temp = new List <MailSummary>();
                var summarys            = await folder.FetchAsync(lowBound, highBound, MessageSummaryItems.Full | MessageSummaryItems.UniqueId);

                for (int i = summarys.Count - 1; i >= 0; i--)
                {
                    temp.Add(new MailSummary(summarys[i].Index, summarys[i].NormalizedSubject, summarys[i].Date, summarys[i].Envelope.Sender));
                }
                return(temp);
            }
            catch
            {
                return(null);
            }
        }
コード例 #19
0
        public List <string> ReceivedFileImap(string SaveToDirectory)
        {
            List <string> file_names = new List <string>();

            using (ImapClient client = new ImapClient())
            {
                client.Connect(IMAPGmailServer, IMAPGmailPort, true);
                client.Authenticate(mailAddress, mailPassword);
                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);
                for (int i = 0; i < inbox.Count; i++)
                {
                    MimeMessage message = inbox.GetMessage(i);
                    if (message.Date.Month == DateTime.Now.Month && message.Date.Day == DateTime.Now.Day && message.Date.Year == DateTime.Now.Year)
                    {
                        IEnumerable <MimeEntity> attachments = message.Attachments;
                        foreach (MimeEntity file in attachments)
                        {
                            file_names.Add(SaveToDirectory + file.ContentType.Name);
                            GetFileImap(file, SaveToDirectory);
                        }
                    }
                }
            }
            logger.WriteLog("Get archives from email", LogLevel.Mail);
            return(file_names);
        }
コード例 #20
0
        // GET api/<controller>
        public IEnumerable <long> Get(string IMAP, int Port, string Login, string Password)
        {
            List <long> list = new List <long>();

            using (ImapClient client = new ImapClient())
            {
                var context = new ELMA3Entities();
                client.Connect(IMAP, Port, SecureSocketOptions.SslOnConnect);
                client.Authenticate(Login, Password);
                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);
                var uids = inbox.Search(SearchQuery.NotSeen);
                foreach (var item in uids)
                {
                    var    message = inbox.GetMessage(item);
                    string a;
                    if (message.HtmlBody != null)
                    {
                        a = message.HtmlBody;
                    }
                    else
                    {
                        a = message.TextBody;
                    }
                    var b = context.CreateEmailMessageI(DateTime.Now.ToString(), DateTime.Now, message.Subject, a, message.Date.UtcDateTime, message.From.FirstOrDefault().Name);
                    list.Add(b.FirstOrDefault().Id);
                }
            }
            return(list.AsEnumerable());
        }
コード例 #21
0
        public static List <Email> GetMails(string username, string password)
        {
            _emails = new List <Email>();
            if (CheckInternet() || System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                using (var client = new ImapClient())
                {
                    client.Connect("imap.gmail.com", 993, true);
                    client.Authenticate(username, password);
                    //The Inbox folder is always available on all IMAP servers...
                    IMailFolder inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly);

                    AddEmailsToList(client);

                    client.Disconnect(true);
                    NewBackup(_emails);
                }
            }
            else
            {
                _emails = LoadBackup();
            }

            _emails.Reverse();
            return(_emails);
        }
コード例 #22
0
        public void GetAllMails(IProgress <MailInfo> progress, [Optional] IMailFolder folder)
        {
            using (ImapClient client = new ImapClient())
            {
                client.Connect(mailServer, port, ssl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(UserData.Email, UserData.Password);

                if (folder == null)
                {
                    folder = client.Inbox;
                }
                else
                {
                    folder = client.GetFolder(folder.FullName);
                }

                folder.Open(FolderAccess.ReadOnly);
                SearchResults results = folder.Search(SearchOptions.All, SearchQuery.DeliveredAfter(DateFrom));

                if (results.UniqueIds.Count < MaxEmails)
                {
                    MaxEmails = results.UniqueIds.Count;
                }

                for (int i = MaxEmails - 1; i >= 0; i--)
                {
                    MailInfo message = new MailInfo(folder.GetMessage(results.UniqueIds[i]), results.UniqueIds[i], folder);
                    progress.Report(message);
                }

                folder.Close();
                client.Disconnect(true);
            }
        }
コード例 #23
0
        public void OpenFolder(IMailFolder folder)
        {
            if (this.folder == folder)
            {
                return;
            }

            if (this.folder != null)
            {
                this.folder.MessageFlagsChanged -= MessageFlagsChanged;
                this.folder.MessageExpunged     -= MessageExpunged;
                this.folder.CountChanged        -= CountChanged;
            }

            folder.MessageFlagsChanged += MessageFlagsChanged;
            folder.MessageExpunged     += MessageExpunged;

            this.folder = folder;

            if (folder.IsOpen)
            {
                LoadMessages();
                return;
            }

            folder.Open(FolderAccess.ReadOnly);
            LoadMessages();
        }
コード例 #24
0
        private void CheckImapMail()
        {
            try
            {
                using (ImapClient imapClient = new ImapClient())
                {
                    imapClient.Connect(_configuration.ServerName, _configuration.Port, _configuration.SSL);
                    imapClient.AuthenticationMechanisms.Remove("XOAUTH2");

                    imapClient.Authenticate(_configuration.UserName, _configuration.Password);

                    IMailFolder inbox = imapClient.Inbox;
                    inbox.Open(FolderAccess.ReadWrite);
                    foreach (UniqueId msgUid in inbox.Search(SearchQuery.NotSeen))
                    {
                        MimeMessage msg = inbox.GetMessage(msgUid);
                        ProcessMail(msg);
                        inbox.SetFlags(msgUid, MessageFlags.Seen, true);
                    }
                }
            }
            catch (Exception ex)
            {
                // Sometimes an error occures, e.g. if the network was disconected or a timeout occured.
                Logger.Instance.LogException(this, ex);
            }
        }
コード例 #25
0
ファイル: Provider.cs プロジェクト: Matioz/JanuszMail
        private UniqueId GetUniqueId(MimeMessage mailMessage, string folder)
        {
            UniqueId    id         = new UniqueId();
            IMailFolder mailFolder = GetFolder(folder);
            bool        open       = mailFolder.IsOpen;

            if (!open)
            {
                mailFolder.Open(FolderAccess.ReadOnly);
            }
            var items = mailFolder.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags);

            foreach (var item in items)
            {
                var message = mailFolder.GetMessage(item.UniqueId);
                if (message.MessageId == mailMessage.MessageId)
                {
                    id = item.UniqueId;
                    break;
                }
            }
            if (!open)
            {
                mailFolder.Close();
            }
            return(id);
        }
コード例 #26
0
        internal IEnumerable <Message> GetMessages()
        {
            _imapFolder.Open(FolderAccess.ReadOnly);
            var messages = _imapFolder.Search(SearchQuery.All).Select(u => new Message(u, _imapFolder.GetHeaders(u))).ToArray();

            _imapFolder.Close();
            return(messages);
        }
コード例 #27
0
        public EmailFolderContext OpenInbox()
        {
            IMailFolder folder = Client.Imap.Inbox;

            folder.Open(FolderAccess.ReadOnly);

            return(new EmailFolderContext(this, folder));
        }
コード例 #28
0
ファイル: Provider.cs プロジェクト: Matioz/JanuszMail
        public void reloadMessages(string folder)
        {
            IMailFolder mailFolder = GetFolder(folder);

            mailFolder.Open(FolderAccess.ReadWrite);
            _currentFolderSummary = mailFolder.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Flags | MessageSummaryItems.Envelope);
            mailFolder.Close();
            _currentFolder = folder;
        }
コード例 #29
0
        public void ReOpen(IMailFolder folder, FolderAccess folderAccess)
        {
            if (folder.IsOpen)
            {
                folder.Close();
            }

            folder.Open(folderAccess);
        }
コード例 #30
0
 /// <summary>
 /// Select a mailbox by name
 /// </summary>
 /// <param name="mailbox">The name of the mailbox</param>
 /// <example>
 /// <code source="../EmailUnitTests/EmailUnitWithDriver.cs" region="SelectMailbox" lang="C#" />
 /// </example>
 public virtual void SelectMailbox(string mailbox)
 {
     GenericWait.WaitFor <bool>(() =>
     {
         CurrentMailBox = mailbox;
         CurrentFolder  = EmailConnection.GetFolder(mailbox);
         CurrentFolder.Open(FolderAccess.ReadWrite);
         return(true);
     });
 }
コード例 #31
0
        private void ProcessRules(IMailFolder inbox) {
            inbox.Open(FolderAccess.ReadWrite);
            inbox.Status(StatusItems.Unread);

            if (inbox.Unread > 0) {
                var unreadMessageUids = inbox.Search(SearchQuery.NotSeen);
                var toMove = new Dictionary<string, List<UniqueId>>();
                var markAsRead = new List<UniqueId>();

                // process unread messages
                foreach (var unreadMessageUid in unreadMessageUids) {
                    var message = inbox.GetMessage(unreadMessageUid);

                    var matchingRule = GetMatchingRule(message);
                    if (matchingRule != null) {
                        if (!toMove.ContainsKey(matchingRule.Destination)) {
                            toMove.Add(matchingRule.Destination, new List<UniqueId>());
                        }

                        toMove[matchingRule.Destination].Add(unreadMessageUid);

                        if (matchingRule.MarkAsRead) {
                            markAsRead.Add(unreadMessageUid);
                        }
                    }
                }

                // mark as read
                if (markAsRead.Any()) {
                    inbox.AddFlags(markAsRead, MessageFlags.Seen, true);
                }

                // move to destination
                if (toMove.Any()) {
                    foreach (var destination in toMove.Keys) {
                        inbox.MoveTo(toMove[destination], inbox.GetSubfolder(destination));
                    }
                }
            }
        }