Beispiel #1
0
 private static void MarkMessagesAsRead(IMailFolder folder, List <IMessageSummary> messages)
 {
     foreach (var message in messages)
     {
         folder.SetFlags(message.UniqueId, MessageFlags.Seen, true);
     }
 }
Beispiel #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);
        }
        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);
            }
        }
Beispiel #4
0
        public void addFlagRead()
        {
            using (var client = new ImapClient())
            {
                client.Connect(Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
                client.AuthenticationMechanisms.Remove(Constant.GoogleOAuth);
                client.Authenticate(Constant.GoogleUserName, Constant.GenericPassword);
                Console.WriteLine(client.IsAuthenticated);


                FolderAccess     inboxAccess = client.Inbox.Open(FolderAccess.ReadWrite);
                IMailFolder      destination = client.GetFolder(Constant.InboxFolder);
                IList <UniqueId> uids        = client.Inbox.Search(SearchQuery.All);

                if (destination != null)
                {
                    for (int i = 0; i < uids.Count; i++)
                    {
                        destination.SetFlags(i, MessageFlags.Seen, true);
                    }

                    Console.WriteLine(uids.Count + "-Marked as Read");
                }
                client.Disconnect(true);
            }
        }
Beispiel #5
0
        /// <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);
            }
        }
Beispiel #6
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);
                }
            }
        }
Beispiel #7
0
        public async Task OpenText(Message m, OpenMessage Page, User user, ConfigModel conf)
        {
            using (ImapClient client = new ImapClient())
            {
                List <string> atc = new List <string>();
                await client.ConnectAsync(conf.ImapServer, conf.ImapPort);

                client.Authenticate(user.Mail, user.Password);
                IMailFolder Folder = client.GetFolder(ListMessages.fold);
                await Folder.OpenAsync(FolderAccess.ReadWrite);

                IList <IMessageSummary> msg = Folder.Fetch(new[] { m.ID }, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure | MessageSummaryItems.Envelope);
                LastOpenId = msg.First().UniqueId;
                var bodyHTML = (TextPart)Folder.GetBodyPart(msg.First().UniqueId, msg.First().HtmlBody);
                Page.Dispatcher.Invoke(() =>
                {
                    Page.Attachments.Children.Clear();
                });
                Folder.SetFlags(m.ID, MessageFlags.Seen, true);
                m.MessageColor = new SolidColorBrush(Colors.White);
                foreach (BodyPartBasic attachment in msg.First().Attachments)
                {
                    Button bt = new Button
                    {
                        Content = attachment.FileName,
                    };
                    Page.Dispatcher.Invoke(() =>
                    {
                        bt.Click += new RoutedEventHandler(new MailWindow(user, conf).OpenAttachment);
                        Page.Attachments.Children.Add(bt);
                    });
                }

                if (m != null)
                {
                    Page.Dispatcher.Invoke(() =>
                    {
                        Page.Info.Text = ($"Subject: {msg.First().Envelope.Subject} \n\rFrom {msg.First().Envelope.From} at {msg.First().Envelope.Date} to {msg.First().Envelope.To}");
                        Page.Body.NavigateToString("<html><head><meta charset='UTF-8'></head>" + bodyHTML.Text + "</html>");
                        Page.MailBody.Visibility = 0;
                    });
                }
                client.Disconnect(true);
            }
        }
Beispiel #8
0
        private UniqueId GetFirstExistingLockMessage(IMailFolder folder, CancellationToken cancellationToken = default)
        {
            folder.Open(FolderAccess.ReadOnly);
            var lockMessages        = folder.Search(SearchQuery.SubjectContains(LockMessageSubject), cancellationToken);
            var orderedLockMessages = lockMessages?.OrderBy(m => m.Id);

            if (orderedLockMessages.Count() > 1)
            {
                var idToRemove = orderedLockMessages.Last();
                try
                {
                    folder.Open(FolderAccess.ReadWrite);
                    folder.SetFlags(idToRemove, MessageFlags.Deleted, true, cancellationToken);
                    folder.Expunge();
                }
                catch
                {
                    logger.Debug("Failed to remove duplicate lock message with ID {0}; note that this might be ok if another client already removed the duplicate", idToRemove);
                }
            }

            return(orderedLockMessages.First());
        }
        private void checkForMails(object sender, ElapsedEventArgs f)
        {
            if (!m_requester)
            {
                return;
            }

            try
            {
                if (m_debug)
                {
                    m_log.Info("[" + Name + "] checkForMails");
                }

                using (var client = new ImapClient())
                {
                    client.CheckCertificateRevocation = false;
                    client.Timeout = 10000;
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    if (IMAP_SERVER_SSL == true)
                    {
                        if (m_debug)
                        {
                            m_log.Info("[" + Name + "] Connect SSL");
                        }

                        client.Connect(IMAP_SERVER_HOSTNAME, IMAP_SERVER_PORT, SecureSocketOptions.Auto);
                    }
                    else if (IMAP_SERVER_TLS == true)
                    {
                        if (m_debug)
                        {
                            m_log.Info("[" + Name + "] Connect TLS");
                        }

                        client.Connect(IMAP_SERVER_HOSTNAME, IMAP_SERVER_PORT, SecureSocketOptions.StartTlsWhenAvailable);
                    }
                    else
                    {
                        if (m_debug)
                        {
                            m_log.Info("[" + Name + "] Connect None");
                        }

                        client.Connect(IMAP_SERVER_HOSTNAME, IMAP_SERVER_PORT, SecureSocketOptions.None);
                    }

                    if (IMAP_SERVER_LOGIN != String.Empty && IMAP_SERVER_PASSWORD != String.Empty)
                    {
                        if (m_debug)
                        {
                            m_log.Info("[" + Name + "] Login with " + IMAP_SERVER_LOGIN + ";" + IMAP_SERVER_PASSWORD);
                        }

                        client.Authenticate(IMAP_SERVER_LOGIN, IMAP_SERVER_PASSWORD);
                    }

                    IMailFolder IMAPInbox = client.Inbox;
                    IMAPInbox.Open(FolderAccess.ReadWrite);

                    if (m_debug)
                    {
                        m_log.Info("[" + Name + "] Found " + IMAPInbox.Count + " messages.");
                    }

                    for (int i = 0; i < IMAPInbox.Count; i++)
                    {
                        MimeMessage message = IMAPInbox.GetMessage(i);
                        foreach (MailboxAddress adress in message.To.Mailboxes)
                        {
                            try
                            {
                                if (m_debug)
                                {
                                    m_log.Info("[" + Name + "] Message To: " + adress.Address);
                                    m_log.Info("[" + Name + "] Objekt ID: " + adress.Address.Split('@')[0]);
                                }

                                String UUIDString = adress.Address.Split('@')[0].Trim();

                                if (isUUID(UUIDString))
                                {
                                    UUID            objID       = UUID.Parse(UUIDString);
                                    SceneObjectPart sceneObject = m_scene.GetSceneObjectPart(objID);

                                    if (sceneObject != null)
                                    {
                                        m_messages.Add(new InternalMail(message, objID));
                                        IMAPInbox.SetFlags(i, MessageFlags.Deleted, true);

                                        if (m_debug)
                                        {
                                            m_log.Info("[" + Name + "] Get Message for objekt " + sceneObject.Name + " (" + sceneObject.UUID + ")");
                                        }
                                    }
                                }
                                else
                                {
                                    IMAPInbox.SetFlags(i, MessageFlags.Deleted, true);
                                }
                            }catch (Exception _innerEroor)
                            {
                                m_log.Error("[" + Name + "] " + _innerEroor.Message);
                                IMAPInbox.SetFlags(i, MessageFlags.Deleted, true);
                            }
                        }
                    }

                    IMAPInbox.Expunge();
                    client.Disconnect(true);
                }
            }catch (Exception _error)
            {
                m_log.Error("[" + Name + "] " + _error.Message);
            }
        }