Example #1
0
        public async Task Attachment(MailWindow inboxPage, User user, ConfigModel conf, string Atch, string destination)
        {
            using (ImapClient client = new ImapClient())
            {
                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> atc = Folder.Fetch(new[] { LastOpenId }, MessageSummaryItems.Body);
                var multipart                 = (BodyPartMultipart)atc.First().Body;
                var attachment                = multipart.BodyParts.OfType <BodyPartBasic>().FirstOrDefault(x => x.FileName == Atch);
                TransferProgress progress     = new TransferProgress();
                Downloads        FileDownload = new Downloads();
                FileDownload.Show();
                var file = Folder.GetBodyPart(LastOpenId, attachment, default, progress);
Example #2
0
        public void TestThreadBadCharsetFallback()
        {
            var badCharsetResponse = Encoding.ASCII.GetBytes("A00000005 NO [BADCHARSET (US-ASCII)] The specified charset is not supported.\r\n");

            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "dovecot.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 LOGIN username password\r\n", "dovecot.authenticate+gmail-capabilities.txt"));
            commands.Add(new ImapReplayCommand("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
            commands.Add(new ImapReplayCommand("A00000004 SELECT INBOX (CONDSTORE)\r\n", "common.select-inbox.txt"));
            //commands.Add (new ImapReplayCommand ("A00000005 UID THREAD REFERENCES US-ASCII \r\n", "dovecot.thread-references.txt"));
            //commands.Add (new ImapReplayCommand ("A00000017 UID THREAD ORDEREDSUBJECT US-ASCII UID 1:* ALL\r\n", "dovecot.thread-orderedsubject.txt"));
            commands.Add(new ImapReplayCommand(Encoding.UTF8, "A00000005 UID THREAD REFERENCES UTF-8 SUBJECT {12+}\r\nпривет\r\n", badCharsetResponse));
            commands.Add(new ImapReplayCommand("A00000006 UID THREAD REFERENCES US-ASCII SUBJECT {6+}\r\n?@825B\r\n", "dovecot.thread-references.txt"));

            using (var client = new ImapClient()) {
                var credentials = new NetworkCredential("username", "password");

                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                // Note: we do not want to use SASL at all...
                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate(credentials);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");

                var inbox = (ImapFolder)client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);

                var threaded = inbox.Thread(ThreadingAlgorithm.References, SearchQuery.SubjectContains("привет"));
                Assert.AreEqual(2, threaded.Count, "Unexpected number of root nodes in threaded results");

                client.Disconnect(false);
            }
        }
Example #3
0
        private void OpenInbox(ImapClient imapClient)
        {
            try
            {
                if (imapClient.IsConnected == false)
                {
                    imapClient.Connect("mail.mobisystems.com", 993, SecureSocketOptions.SslOnConnect, default);
                    imapClient.Authenticate("*****@*****.**", "T%est654!!321");
                }

                imapClient.Inbox.Open(FolderAccess.ReadWrite);
            }
            catch (Exception ex)
            {
                Logger.Log($"Exception {id}: {ex.Message}");
            }
        }
Example #4
0
        private void FillMyTreeView()
        {
            // Suppress repainting the TreeView until all the objects have been created.
            treeView2.BeginUpdate();

            // Clear the TreeView each time the method is called.
            treeView2.Nodes.Clear();

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

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

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate(SendEmailMIMEKIT.selfUserName, SendEmailMIMEKIT.selfKeyWord);

                // Get the first personal namespace and list the toplevel folders under it.
                // Add a root TreeNode for each Folder object in the ArrayList.
                var personal = client.GetFolder(client.PersonalNamespaces[0]);
                foreach (var folder in personal.GetSubfolders(false))
                {
                    TreeNode tempNode = new TreeNode(folder.Name);
                    tempNode.Name = folder.Name;
                    treeView2.Nodes.Add(tempNode);
                    int i = 0;
                    // Add a child treenode for each SubFolder object in the current Folder object.
                    foreach (var foldery in folder.GetSubfolders(false))
                    {
                        TreeNode tempNode2 = new TreeNode(foldery.Name);
                        tempNode2.Name = foldery.Name;
                        treeView2.Nodes[i].Nodes.Add(
                            tempNode2);
                    }
                    i++;
                }

                client.Disconnect(true);
            }
            // Begin repainting the TreeView.
            treeView2.EndUpdate();
        }
        public static List <string> SearchInInbox()
        {
            List <string> Messages = new List <string>();

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

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

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate(SendEmailMIMEKIT.selfUserName, SendEmailMIMEKIT.selfKeyWord);

                // The Inbox folder is always available on all IMAP servers...
                var inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                Console.WriteLine("Total messages: {0}", inbox.Count);
                Console.WriteLine("Recent messages: {0}", inbox.Recent);
                string temp  = String.Format("Total messages: {0}", inbox.Count);
                string temp2 = String.Format("Recent messages: {0}", inbox.Recent);

                Messages.Add(inbox.Count.ToString());
                Messages.Add(inbox.Recent.ToString());

                // let's search for all messages received after Jan 12, 2013 with "MailKit" in the subject...
                var query = SearchQuery.DeliveredAfter(DateTime.Parse("2013-01-12"))
                            .And(SearchQuery.SubjectContains("Google")).And(SearchQuery.Seen);

                foreach (var uid in inbox.Search(query))
                {
                    var message = inbox.GetMessage(uid);
                    Console.WriteLine("[match] {0}: {1}", uid, message.Subject);
                    string temp3 = String.Format("[match] {0}: {1}", uid, message.Subject);
                    Messages.Add(temp3);
                }

                client.Disconnect(true);

                return(Messages);
            }
        }
        public void MarkAsUnRead(MailInfo mail)
        {
            using (ImapClient client = new ImapClient())
            {
                client.Connect(mailServer, port, ssl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(UserData.Email, UserData.Password);

                IMailFolder folder = client.GetFolder(mail.ParentFolder.FullName);
                folder.Open(FolderAccess.ReadWrite);
                folder.RemoveFlags(new List <UniqueId> {
                    mail.Uid
                }, MessageFlags.Seen, true);
                folder.Close();
                client.Disconnect(true);
            }
        }
Example #7
0
        private void Connect(ImapClient client)
        {
            client.ServerCertificateValidationCallback = (s, c, h, e) => true;
            if (!client.IsConnected)
            {
                logger.LogTrace($"Connecting");
                client.Connect(server, port, imapSecure);
                logger.LogInformation($"Connected");
            }

            if (!client.IsAuthenticated)
            {
                logger.LogTrace($"Authenticating");
                client.Authenticate(username, password);
                logger.LogInformation($"Authenticated");
            }
        }
Example #8
0
 public bool IsCorrectLoginCredentials(string username, string password)
 {
     try
     {
         using (var client = new ImapClient())
         {
             client.Connect("imap.gmail.com", 993, true);
             client.Authenticate(username, password);
             client.Disconnect(true);
             return(true);
         }
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public List <String> getFolders()
        {
            List <String> folders = new List <string>();

            using (var client = new ImapClient())
            {
                try
                {
                    client.Connect(mailServer, port, ssl);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(login, password);

                    var mainEmailFolder = client.GetFolder(client.PersonalNamespaces[0]);
                    emailFolders = mainEmailFolder.GetSubfolders().ToList();

                    foreach (var folder in emailFolders)
                    {
                        int count = 0;
                        try
                        {
                            folder.Open(FolderAccess.ReadOnly);

                            var uids = folder.Search(SearchQuery.All);
                            foreach (var uid in uids)
                            {
                                count++;
                            }
                            //var results = folder.Search(SearchOptions.Count, SearchQuery.All);
                            //var c = results.UniqueIds.Count;
                            folders.Add(folder.FullName + " (" + count + ")");
                            folder.Close();
                        }
                        catch
                        {
                            MessageBox.Show("");
                        }
                    }
                }
                catch (AuthenticationException)
                {
                    MessageBox.Show("Wrong username or password.");
                }

                return(folders);
            }
        }
Example #10
0
 public bool connect()
 {
     try
     {
         client.Connect(mailServer, port, ssl);
         // Note: since we don't have an OAuth2 token, disable
         // the XOAUTH2 authentication mechanism.
         client.AuthenticationMechanisms.Remove("XOAUTH2");
         client.Authenticate(login, password);
         return(true);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
     }
     return(false);
 }
        public void TestAppendWithAnnotations(bool withInternalDates)
        {
            var expectedFlags          = MessageFlags.Answered | MessageFlags.Flagged | MessageFlags.Deleted | MessageFlags.Seen | MessageFlags.Draft;
            var expectedPermanentFlags = expectedFlags | MessageFlags.UserDefined;
            List <DateTimeOffset> internalDates;
            List <Annotation>     annotations;
            List <MimeMessage>    messages;
            List <MessageFlags>   flags;

            var commands = CreateAppendWithAnnotationsCommands(withInternalDates, out messages, out flags, out internalDates, out annotations);

            using (var client = new ImapClient()) {
                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate("username", "password");
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                for (int i = 0; i < messages.Count; i++)
                {
                    UniqueId?uid;

                    if (withInternalDates)
                    {
                        uid = client.Inbox.Append(messages[i], flags[i], internalDates[i], new [] { annotations[i] });
                    }
                    else
                    {
                        uid = client.Inbox.Append(messages[i], flags[i], null, new [] { annotations[i] });
                    }

                    Assert.IsTrue(uid.HasValue, "Expected a UIDAPPEND resp-code");
                    Assert.AreEqual(i + 1, uid.Value.Id, "Unexpected UID");
                }

                client.Disconnect(true);
            }
        }
Example #12
0
        public static void UsingClient(Action <ImapClient> action)
        {
            var client = new ImapClient();

            try
            {
                var config = Config.Get <MailSettings>();
                client.Connect(config.ImapHost, config.ImapPort, MailKit.Security.SecureSocketOptions.SslOnConnect);
                client.Authenticate(config.Username, config.Password);

                action(client);
            }
            finally
            {
                client.Disconnect(true);
            }
        }
        public ICollection <string> GetHtmlMessages()
        {
            using (var client = new ImapClient())
            {
                client.Connect(_applicationSettings.ImapHost, _applicationSettings.ImapPort, true);
                client.Authenticate(_applicationSettings.ImapLogin, _applicationSettings.ImapPassword);

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

                var searchResult = inbox.Search(SearchOptions.All, SearchQuery.BodyContains("Вы заказали такси").And(SearchQuery.BodyContains("Отчёт о поездке")).And(SearchQuery.FromContains("*****@*****.**")));
                var messages     = searchResult.UniqueIds.Select(uid => inbox.GetMessage(uid).HtmlBody).ToList();
                client.Disconnect(true);

                return(messages);
            }
        }
Example #14
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);
            }
        }
Example #15
0
        /// <summary>
        /// Will Download both the attachments and inline attachments in one single directory
        /// Will not OVERWRITE files that have the same filenames
        /// </summary>
        public void DownloadAttachmentsFileIoWay()
        {
            using (var client = new ImapClient())
            {
                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);
                IList <UniqueId> uids = client.Inbox.Search(SearchQuery.All);
                int anotherOne        = 0;

                foreach (UniqueId uid in uids)
                {
                    MimeMessage message = client.Inbox.GetMessage(uid);

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

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

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

                            Console.WriteLine("Downloaded: " + fileName);
                        }
                    }
                }
            }
        }
Example #16
0
        public static Mail[] GetMail()
        {
            List <Mail> messages   = new List <Mail>();
            int         inboxCount = 0;

            using (var client = new ImapClient())
            {
                client.Connect("imap.yandex.ru", 993, true);
                client.Authenticate("somelogin", "somepassword");

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

                var query = SearchQuery.DeliveredAfter(DateTime.Now - TimeSpan.FromDays(2));
                var uids  = client.Inbox.Search(query);

                var fields = new HashSet <string>();
                fields.Add("Received");
                var f = inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope | MessageSummaryItems.InternalDate | MessageSummaryItems.UniqueId, fields);

                foreach (var ff in f)
                {
                    var m  = new Mail();
                    var mm = inbox.GetMessage(ff.UniqueId);

                    m.Subject     = mm.Subject;
                    m.SendDate    = ff.Date.ToString();
                    m.ReceiveDate = ff.InternalDate.ToString();
                    m.Id          = mm.MessageId;

                    messages.Add(m);
                }

                /*for (int i = inbox.Count - 1; i >= (inbox.Count - 10); i--) {
                 *  var message = inbox.GetMessage(i);
                 *  message.da
                 *  messages.Add(m);
                 *  //Console.WriteLine("Subject: {0}", message.Subject);
                 * }*/

                client.Disconnect(true);
            }

            return(messages.ToArray());
        }
Example #17
0
        public void TestSearchStringWithSpaces()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "yahoo.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 LOGIN username password\r\n", ImapReplayCommandResponse.OK));
            commands.Add(new ImapReplayCommand("A00000001 CAPABILITY\r\n", "yahoo.capabilities.txt"));
            commands.Add(new ImapReplayCommand("A00000002 NAMESPACE\r\n", "yahoo.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST \"\" \"INBOX\"\r\n", "yahoo.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000004 EXAMINE Inbox\r\n", "yahoo.examine-inbox.txt"));
            commands.Add(new ImapReplayCommand(Encoding.UTF8, "A00000005 UID SEARCH SUBJECT \"Yahoo Mail\"\r\n", "yahoo.search.txt"));

            using (var client = new ImapClient()) {
                var credentials = new NetworkCredential("username", "password");

                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                // Note: we do not want to use SASL at all...
                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate(credentials);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");

                var inbox = (ImapFolder)client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                var uids = inbox.Search(SearchQuery.SubjectContains("Yahoo Mail"));
                Assert.AreEqual(14, uids.Count);
                for (int i = 0; i < uids.Count; i++)
                {
                    Assert.AreEqual(i + 1, uids[i].Id);
                }

                client.Disconnect(false);
            }
        }
Example #18
0
        /// <summary>
        /// Log in to the IMAP server and perform the given action.
        /// </summary>
        /// <param name="action">Action to perform.</param>
        protected void LoginAndRunAction(Action <ImapClient> action)
        {
            Console.Write("Connecting to IMAP server... ");
            using (var client = new ImapClient())
            {
                client.Connect(_config.Hostname, _config.Port, _config.UseSsl);
                Console.WriteLine("Connected!");
                Console.Write("Logging in... ");
                client.Authenticate(_config.Username, _config.Password);
                Console.WriteLine("Logged in!");

                action(client);

                Console.Write("Logging out... ");
                client.Disconnect(true);
                Console.WriteLine("Logged out!");
            }
        }
Example #19
0
        public void ReceiveMails()
        {
            using (var client = new ImapClient())
            {
                client.Connect(this.ImapClientHost, this.ImapClientPort, false);
                client.Authenticate(this.UserAddress, this.Password);
                client.Inbox.Open(FolderAccess.ReadOnly);
                var uids = client.Inbox.Search(SearchQuery.All);
                foreach (var uid in uids)
                {
                    var message = client.Inbox.GetMessage(uid);
                    Console.WriteLine(message.TextBody);
                    // message.WriteTo($"{uid}.eml");
                }

                client.Disconnect(true);
            }
        }
Example #20
0
 public static void Get()
 {
     using (var client = new ImapClient()) {
         client.Connect("imap.gmail.com", 993, true);
         client.AuthenticationMechanisms.Remove("XOAUTH2");
         client.Authenticate("account name", "password");
         var inbox = client.Inbox;
         inbox.Open(FolderAccess.ReadOnly);
         Console.WriteLine("Total messages: {0}", inbox.Count);
         Console.WriteLine("Recent messages: {0}", inbox.Recent);
         for (var i = 0; i < inbox.Count; i++)
         {
             var message = inbox.GetMessage(i);
             Console.WriteLine("Subject: {0}", message.Subject);
         }
         client.Disconnect(true);
     }
 }
Example #21
0
        public void DeteleEmail(string id)
        {
            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("imap.gmail.com", 993, true);
                client.Authenticate("*****@*****.**", "PawelNa100%");

                var inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);
                var uids = inbox.Search(SearchQuery.HeaderContains("Message-Id", id));
                inbox.AddFlags(uids, MessageFlags.Deleted, silent: true);


                client.Disconnect(true);
            }
        }
Example #22
0
        /// <summary>
        /// 打开邮箱文件夹
        /// </summary>
        /// <param name="mailFromAccount">邮箱账号</param>
        /// <param name="mailPassword">邮箱密码</param>
        /// <param name="folderName">文件夹名称(INBOX:收件箱名称)</param>
        /// <returns></returns>
        public static IMailFolder OpenFolder(string mailFromAccount, string mailPassword, string folderName)
        {
            ImapClient client = new ImapClient();

            client.Connect(ImapServer, ImapPort);

            client.Authenticate(mailFromAccount, mailPassword);

            //获取所有文件夹
            //List<IMailFolder> mailFolderList = client.GetFolders(client.PersonalNamespaces[0]).ToList();

            var folder = client.GetFolder(folderName);

            //打开文件夹并设置为读的方式
            folder.Open(FolderAccess.ReadWrite);

            return(folder);
        }
        /// <summary>
        /// - Создание клиента, его запуск;
        /// - Загрузка сообщений;
        /// - Обработка сообщений;
        /// - Удаление сообщений;
        /// </summary>
        public override void ProcessData()
        {
            if (!configured)
            {
                return;
            }

            using (var client = new ImapClient()) {
                var credential = new NetworkCredential(settings.MailKitClientUser, settings.MailKitClientPass);
                client.Connect(new Uri(settings.IMAPUrl), Cancellation);
                //что бы не спамить логи почтового сервера
                client.AuthenticationMechanisms.Clear();
                client.AuthenticationMechanisms.Add("PLAIN");
                client.Authenticate(credential, Cancellation);
                var imapFolder = String.IsNullOrEmpty(settings.IMAPSourceFolder) ? client.Inbox : client.GetFolder(settings.IMAPSourceFolder);
                if (imapFolder == null)
                {
                    var root = client.GetFolder(client.PersonalNamespaces[0]);
                    imapFolder = root.Create(settings.IMAPSourceFolder, true, Cancellation);
                }
                imapFolder.Open(FolderAccess.ReadWrite, Cancellation);
                var ids = imapFolder.Search(SearchQuery.All, Cancellation);
#if !DEBUG
                using (var session = SessionHelper.GetSessionFactory().OpenSession()) {
#endif
                foreach (var id in ids)
                {
                    var message = imapFolder.GetMessage(id, Cancellation);
                    try {
                        ProcessMessage(session, message, id);
                    } catch (Exception e) {
                        _logger.Error($"Не удалось обработать письмо {message}", e);
                    } finally {
                        imapFolder.SetFlags(id, MessageFlags.Deleted, true, Cancellation);
                    }
                    Cleanup();
                }
#if !DEBUG
            }
#endif
                imapFolder.Close(true, Cancellation);
                client.Disconnect(true, Cancellation);
            }
        }
        public async void SendVaccineAvailability(Location location, User user)
        {
            using (var smtpClient = new SmtpClient())
            {
                using (var client = new ImapClient())
                {
                    client.Connect(mailServer, port, ssl);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(login, password);

                    smtpClient.Connect("smtp.gmail.com", 587);
                    smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
                    smtpClient.Authenticate(login, password);

                    var inbox = client.Inbox;
                    var reply = new MimeMessage();
                    reply.To.Add(MailboxAddress.Parse(user.Email));
                    reply.From.Add(MailboxAddress.Parse("*****@*****.**"));

                    if (user.PhoneNumber != null)
                    {
                        reply.To.Add(MailboxAddress.Parse(user.PhoneNumber));
                    }


                    reply.Subject = "Vaccine Availability";

                    string text = String.Format("Vaccine availability at {0} in {1}, {2} {3}.", location.name, location.address.city, location.address.state, location.address.zip);
                    text += "<br />";
                    text += string.Format("https://www.hy-vee.com/my-pharmacy/covid-vaccine-consent");

                    var bodyBuilder = new BodyBuilder();
                    bodyBuilder.HtmlBody = string.Format("<span style='font-size:12.0pt;font-family:\"Courier New\" '>{0}</span>", text);


                    reply.Body = bodyBuilder.ToMessageBody();
                    smtpClient.Send(reply);
                }
            }
        }
Example #25
0
        public Task <List <Message> > PaerserEmailAsync(Setting setting, ISoapService soapService)
        {
            List <Message> messages = new List <Message>();

            using (var client = new ImapClient())
            {
                client.Connect(setting.ImapServer, setting.ImapPort, SecureSocketOptions.SslOnConnect);

                client.Authenticate(setting.InputMail, setting.InputMailPassword);

                client.Inbox.Open(FolderAccess.ReadWrite);

                var uids = client.Inbox.Search(SearchQuery.New);
                uids = client.Inbox.Search(SearchQuery.NotSeen);

                foreach (var uid in uids)
                {
                    var message = client.Inbox.GetMessage(uid);

                    if (message.Subject == setting.Subject)
                    {
                        var ItemRegex    = new Regex(setting.RegexMask, RegexOptions.Compiled);
                        var AllParamList = ItemRegex.Matches(message.TextBody)
                                           .Cast <Match>()
                                           .Select(m => new
                        {
                            Name  = m.Groups[1].ToString(),
                            Value = m.Groups[2].ToString()
                        })
                                           .ToList();
                        var paramList = AllParamList.Join(setting.ParamSettings, ap => ap.Name, cp => cp.FullName, (paramsetting, parammessage) => new ParamMessage {
                            Name = parammessage.Name, Value = paramsetting.Value
                        }).ToList();
                        var resultService = soapService.SendRequest(setting, paramList);
                        if (resultService == "sucsess")
                        {
                            client.Inbox.AddFlags(uid, MessageFlags.Seen, true);
                        }
                    }
                }
                client.Disconnect(true);
            }
            return(Task.Run(() => messages));;
        }
Example #26
0
        public void TestSearchAnnotations()
        {
            var commands = CreateSearchAnnotationsCommands();

            using (var client = new ImapClient()) {
                var credentials = new NetworkCredential("username", "password");

                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                // Note: we do not want to use SASL at all...
                client.AuthenticationMechanisms.Clear();

                try {
                    client.Authenticate(credentials);
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");

                var inbox = (ImapFolder)client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);

                Assert.AreEqual(AnnotationAccess.ReadOnly, inbox.AnnotationAccess, "AnnotationAccess");
                Assert.AreEqual(AnnotationScope.Both, inbox.AnnotationScopes, "AnnotationScopes");
                Assert.AreEqual(0, inbox.MaxAnnotationSize, "MaxAnnotationSize");

                var query = SearchQuery.AnnotationsContain(AnnotationEntry.Comment, AnnotationAttribute.Value, "a comment");
                var uids  = inbox.Search(query);

                Assert.AreEqual(14, uids.Count, "Unexpected number of UIDs");

                // disable ANNOTATE-EXPERIMENT-1 and try again
                client.Capabilities &= ~ImapCapabilities.Annotate;

                Assert.Throws <NotSupportedException> (() => inbox.Search(query));

                client.Disconnect(false);
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            using (var client = new ImapClient())
            {
                // Для демонстрационных целей, принимать все SSL сертификаты
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("imap.yandex.ru", 993, true);
                client.Authenticate("*****@*****.**", "1Qwerty");

                // Проверка подключения к серверу
                // Доделать потом (если нет подключения, что то делать)
                //if (client.IsConnected == true)
                // {
                // Папка «Входящие» всегда доступна на всех серверах IMAP ...
                var inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadWrite);

                // Ищем новые сообщения не прочитанные
                foreach (var uid in inbox.Search(SearchQuery.NotSeen))
                {
                    // Получаем не прочитанное письмо
                    var message = inbox.GetMessage(uid);
                    foreach (MimeEntity attachment in message.Attachments)
                    {
                        // Узнаем имя вложения
                        string contentname = null;

                        if (attachment.ContentDisposition.FileName != null)
                        {
                            contentname = attachment.ContentDisposition.FileName;
                        }
                        var fileName = contentname ?? attachment.ContentType.Name;

                        // Имя файла
                        Console.WriteLine(fileName);
                    }
                    // Изменение статуса письма с "не прочитанно" => "прочитано
                    inbox.AddFlags(uid, MessageFlags.Seen, true);
                }
                client.Disconnect(true);
                Console.ReadLine();
            }
        }
Example #28
0
        static void Main(string[] args)
        {
            //创建获取邮件客户端并连接到邮件服务器
            ImapClient client = new ImapClient();

            //client.Connect("mail.gildata.com");
            //必须调用该事件获取服务器证书,否则无法正常连接
            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
            //带端口号和协议的连接方式
            client.Connect("imap.gildata.com", 993, true);
            string account  = "*****@*****.**";
            string passWord = "******";

            client.Authenticate(account, passWord);
            //获取所有文件夹
            List <IMailFolder> mailFolderList = client.GetFolders(client.PersonalNamespaces[0]).ToList();
            //获取收件箱文件夹
            var folder = client.GetFolder("INBOX");

            //以只读方式打开文件夹
            folder.Open(MailKit.FolderAccess.ReadOnly);
            //选出日期在2019-03-14后的邮件
            var uidss = folder.Search(SearchQuery.DeliveredAfter(DateTime.Parse("2019-03-14")));

            folder.Fetch(uidss, MessageSummaryItems.UniqueId | MessageSummaryItems.Full);
            foreach (var item in uidss)
            {
                MimeMessage message = folder.GetMessage(new UniqueId(item.Id));
                foreach (MimePart attachment in message.Attachments)
                {
                    //下载附件
                    using (var cancel = new System.Threading.CancellationTokenSource())
                    {
                        string filePath = Path.Combine(".", attachment.FileName);
                        using (var stream = File.Create(filePath))
                        {
                            attachment.ContentObject.DecodeTo(stream, cancel.Token);
                        }
                    }
                }
            }
            //关闭文件
            folder.Close();
        }
        public void GetAllMails(IProgress <MimeMessage> progress)
        {
            var messages = new List <MimeMessage>();

            using (var client = new ImapClient())
            {
                try
                {
                    client.Connect(mailServer, port, ssl);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(login, password);

                    var mainEmailFolder = client.GetFolder(client.PersonalNamespaces[0]);
                    emailFolders = mainEmailFolder.GetSubfolders().ToList();

                    var inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly);
                    var results      = inbox.Search(SearchOptions.All, SearchQuery.DeliveredAfter(new DateTime(2019, 08, 01)));
                    int emailCounter = results.UniqueIds.Count;
                    if (emailCounter > 50)
                    {
                        emailCount = 50;
                    }
                    else
                    {
                        emailCount = results.UniqueIds.Count;
                    }

                    for (int i = emailCounter - 1; i >= emailCounter - emailCount; i--)
                    {
                        var message = inbox.GetMessage(results.UniqueIds[i]);
                        progress.Report(message);
                        messages.Add(message);
                    }

                    client.Disconnect(true);
                }
                catch (AuthenticationException)
                {
                    MessageBox.Show("Wrong username or password.");
                }
            }
            //return messages;
        }
Example #30
0
        public Master(string configFileName)
        {
            _config = new MailFilterConfig();
            _config.Load(configFileName);
            _logger = new Logger(_config.LogFilePrefix);
            _logger.Info("Mail Filter programm started.");

            _imap = new ImapClient();
            _imap.Connect(_config.Imap.ImapServerHost, _config.Imap.ImapServerPort, true);
            _logger.Info("IMAP connected.");
            _imap.Authenticate(_config.Imap.MailAccountName, _config.Imap.MailAccountPassword);
            _logger.Info("IMAP autenticated.");
            _imap.Inbox.Open(FolderAccess.ReadWrite);
            _logger.Notice("IMAP inbox folder opened.");

            var context = new Context(_imap, _logger);

            _processor = new MasterProcessor(context, _config);
        }