private void SignIn(object obj)
        {
            PasswordBox pwBox = obj as PasswordBox;

            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    while (true)
                    {
                        DisplayAndShowIcon("Connecting...", (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build);
                        InitializeClient(pwBox);
                        DisplayMessage("Connected");
                        reconnectEvent.WaitOne();
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                }
            });
        }
示例#2
0
        /*Initializin Error Email*/


        /*Initializin Buy Email*/
        static void InitializeBuyClient()
        {
            if (BuyClient != null)
            {
                BuyClient.Dispose();
            }
            BuyClient             = new ImapClient("imap.gmail.com", 993, SettingsForm.BuyEmailAdress, SettingsForm.BuyEmailAdressPw, AuthMethod.Login, true);
            BuyClient.NewMessage += BuyClient_NewMessage1;
            BuyClient.IdleError  += BuyClient_IdleError;
        }
示例#3
0
        public void Revoke()
        {
            _credential = null;

            if (_email != null)
            {
                _email.Logout();
                _email.Dispose();
                _email = null;
            }
        }
示例#4
0
        /*Initializin Sell Email*/
        public static void InitializSellClient()
        {
            if (SellClient != null)
            {
                SellClient.Dispose();
            }
            SellClient = new ImapClient("imap.gmail.com", 993, SettingsForm.SellEmailAdress, SettingsForm.SellEmailAdressPw, AuthMethod.Login, true);


            SellClient.NewMessage += SellClient_NewMessage1;
            SellClient.IdleError  += SellClient_IdleError;
        }
示例#5
0
        /// <summary>
        /// Establishes connection to mail server depending on user type and creates
        /// a new <see cref="T:MailKit.Net.Imap.ImapClient" /> instance
        /// </summary>
        /// <param name="userType">User type (see <see cref="T:Common.Enums.UserType"/>)</param>
        public Task ConnectMailServerAsync(UserType userType)
        {
            return(Task.Run(() =>
            {
                switch (userType)
                {
                case UserType.AdminCxM:
                    ClientCxM?.Dispose();
                    ClientCxM = new ImapClient
                    {
                        ServerCertificateValidationCallback = (s, c, h, e) => true
                    };

                    try
                    {
                        ClientCxM.Connect(TestConfig.MailServerDomain, TestConfig.MailServerPort);
                        ClientCxM.Authenticate(TestConfig.MailServerLogin, TestConfig.MailServerPassword);
                        ClientCxM.Inbox.Open(FolderAccess.ReadWrite);
                    }
                    catch (Exception ex)
                    {
                        throw new AggregateException($"Mail server error: {ex.Message}");
                    }

                    break;

                case UserType.AdminUserDirectory:
                    ClientUserDirectory?.Dispose();
                    ClientUserDirectory = new ImapClient
                    {
                        ServerCertificateValidationCallback = (s, c, h, e) => true
                    };
                    try
                    {
                        ClientUserDirectory.Connect(TestConfig.MailServerDomainAdmin,
                                                    TestConfig.MailServerPortAdmin);
                        ClientUserDirectory.Authenticate(TestConfig.MailServerLoginAdmin,
                                                         TestConfig.MailServerPasswordAdmin);
                        ClientUserDirectory.Inbox.Open(FolderAccess.ReadWrite);
                    }
                    catch (Exception ex)
                    {
                        throw new AggregateException($"Mail server error: {ex.Message}");
                    }

                    break;
                }
            }));
        }
        public static void Run()
        {
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // ExStart:ListMessagesAsynchronouslyWithMailQuery
                ImapQueryBuilder builder = new ImapQueryBuilder();
                builder.Subject.Contains("Subject");
                MailQuery    query                 = builder.GetQuery();
                IAsyncResult asyncResult           = client.BeginListMessages(query);
                ImapMessageInfoCollection messages = client.EndListMessages(asyncResult);
                // ExEnd:ListMessagesAsynchronouslyWithMailQuery

                Console.WriteLine("New Message Added Successfully");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
        }
        public static void Run()
        {
            //ExStart:SSLEnabledIMAPServer
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();
            // Specify host, username and password, Port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                Console.WriteLine("Logged in to the IMAP server");
                // Disconnect to the remote IMAP server
                client.Dispose();
                Console.WriteLine("Disconnected from the IMAP server");
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:SSLEnabledIMAPServer
            Console.WriteLine(Environment.NewLine + "Connected to IMAP server with SSL.");
        }
        // ExStart:ReadMessagesRecursively
        public static void Run()
        {
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // The root folder (which will be created on disk) consists of host and username
                string rootFolder = client.Host + "-" + client.Username;

                // Create the root folder and List all the folders from IMAP server
                Directory.CreateDirectory(rootFolder);
                ImapFolderInfoCollection folderInfoCollection = client.ListFolders();
                foreach (ImapFolderInfo folderInfo in folderInfoCollection)
                {
                    // Call the recursive method to read messages and get sub-folders
                    ListMessagesInFolder(folderInfo, rootFolder, client);
                }
                // Disconnect to the remote IMAP server
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }

            Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server.");
        }
        public static void Run()
        {
            // ExStart:FilteringMessagesFromIMAPMailbox
            // Connect and log in to IMAP
            const string host     = "host";
            const int    port     = 143;
            const string username = "******";
            const string password = "******";
            ImapClient   client   = new ImapClient(host, port, username, password);

            client.SelectFolder("Inbox");
            // Set conditions, Subject contains "Newsletter", Emails that arrived today
            ImapQueryBuilder builder = new ImapQueryBuilder();

            builder.Subject.Contains("Newsletter");
            builder.InternalDate.On(DateTime.Now);
            // Build the query and Get list of messages
            MailQuery query = builder.GetQuery();
            ImapMessageInfoCollection messages = client.ListMessages(query);

            Console.WriteLine("Imap: " + messages.Count + " message(s) found.");
            // Disconnect from IMAP
            client.Dispose();
            // ExEnd:FilteringMessagesFromIMAPMailbox
        }
示例#10
0
        private bool disposedValue = false; // To detect redundant calls

        protected async virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    if (_mailFolder != null && _mailFolder.IsOpen)
                    {
                        await _mailFolder.CloseAsync();
                    }
                    if (_imapClient?.IsConnected == true)
                    {
                        await _imapClient.DisconnectAsync(true);

                        _imapClient.Dispose();
                    }
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.
                _lastRetrievedUIds = null;
                _mailFolder        = null;
                _mailFolders       = null;

                disposedValue = true;
            }
        }
示例#11
0
        public static void Run()
        {
            //ExStart:SSLEnabledIMAPServer
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username and password, Port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                Console.WriteLine("Logged in to the IMAP server");
                // Disconnect to the remote IMAP server
                client.Dispose();
                Console.WriteLine("Disconnected from the IMAP server");
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:SSLEnabledIMAPServer
            Console.WriteLine(Environment.NewLine + "Connected to IMAP server with SSL.");
        }
 //connect to server
 public void ConnectToServer(EmailBoxAkkaut account)
 {
     //#1 try connect to server on right port and domen
     try
     {
         _imapClient         = new ImapClient();
         _imapClient.Timeout = 20000;
         _logger.Info($"{_libName} try connnect to server");
         _imapClient.Connect(account.Server, account.Port, SecureSocketOptions.None);
         _logger.Info($"{_libName} Connected to server");
         account.ServerStatus = GoodState;
     }
     catch (Exception ex)
     {
         _logger.Error(ex.Message);
         account.ServerStatus = ex.Message;
         return;
     }
     //#2 try authenticate on server
     try{
         _imapClient.Authenticate(account.Login, account.Pass);
         _logger.Info($"{_libName} Try auth to server");
         _imapClient.Inbox.Open(FolderAccess.ReadWrite);
         _logger.Info($"{_libName} Authenticated");
         account.AccountStatus = GoodState;
     }
     catch (Exception ex)
     {
         _logger.Error(ex.Message);
         account.AccountStatus = ex.Message;
         _imapClient.Dispose();
     }
 }
示例#13
0
        public void Dispose()
        {
            cancel.Cancel();

            client.Dispose();
            cancel.Dispose();
        }
示例#14
0
        public List <GmailAPIService.CurrentMessage> GetAllMessages(string mail, string password)
        {
            List <GmailAPIService.CurrentMessage> messagesInfo = new List <GmailAPIService.CurrentMessage>();

            ImapClient ic = new ImapClient("imap.gmail.com", mail, password,
                                           AuthMethods.Login, 993, true);

            ic.SelectMailbox("INBOX");

            int messageCount = ic.GetMessageCount();

            MailMessage[] mm = ic.GetMessages(messageCount, messageCount - 30);
            foreach (MailMessage m in mm)
            {
                messagesInfo.Add(new GmailAPIService.CurrentMessage()
                {
                    Id      = m.MessageID.Replace('<', '"').Replace('>', '"'),
                    Date    = m.Date.ToString(),
                    From    = m.From.ToString(),
                    Subject = m.Subject
                });
            }
            ic.Dispose();
            return(messagesInfo);
        }
示例#15
0
        public static void Run()
        {
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username and password, and set port for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // ExStart:DeletingAndRenamingFolders
                // Delete a folder and Rename a folder
                client.DeleteFolder("foldername");
                client.RenameFolder("foldername", "newfoldername");
                // ExEnd:DeletingAndRenamingFolders

                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
        }
示例#16
0
 public void Dispose()
 {
     _smtp.Disconnect(true);
     _imap.Disconnect(true);
     _smtp.Dispose();
     _imap.Dispose();
 } //Used to dispose of the email clients.
        public static void Run()
        {
            // Connect and log in to IMAP
            const string host     = "host";
            const int    port     = 143;
            const string username = "******";
            const string password = "******";
            ImapClient   client   = new ImapClient(host, port, username, password);

            try
            {
                client.SelectFolder("Inbox");

                // ExStart:SpecifyEncodingForQueryBuilder
                // Set conditions
                ImapQueryBuilder builder = new ImapQueryBuilder(Encoding.UTF8);
                builder.Subject.Contains("ğüşıöç", true);
                MailQuery query = builder.GetQuery();
                // ExEnd:SpecifyEncodingForQueryBuilder

                // Get list of messages
                ImapMessageInfoCollection messages = client.ListMessages(query);
                foreach (ImapMessageInfo info in messages)
                {
                    Console.WriteLine("Message Id: " + info.MessageId);
                }

                // Disconnect from IMAP
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public static void Run()
        {
            //ExStart:DeletingFolders
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username and password, and set port for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // Rename a folder and Disconnect to the remote IMAP server
                client.DeleteFolder("Client");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:DeletingFolders
            Console.WriteLine(Environment.NewLine + "Deleted folders on IMAP server.");
        }
示例#19
0
        public static void Run()
        {
            //ExStart:DeletingFolders
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username and password, and set port for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // Rename a folder and Disconnect to the remote IMAP server
                client.DeleteFolder("Client");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:DeletingFolders
            Console.WriteLine(Environment.NewLine + "Deleted folders on IMAP server.");
        }
        // ExStart:ReadMessagesRecursively
        public static void Run()
        {
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // The root folder (which will be created on disk) consists of host and username
                string rootFolder = client.Host + "-" + client.Username;

                // Create the root folder and List all the folders from IMAP server
                Directory.CreateDirectory(rootFolder);
                ImapFolderInfoCollection folderInfoCollection = client.ListFolders();
                foreach (ImapFolderInfo folderInfo in folderInfoCollection)
                {
                    // Call the recursive method to read messages and get sub-folders
                    ListMessagesInFolder(folderInfo, rootFolder, client);
                }
                // Disconnect to the remote IMAP server
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }

            Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server.");
        }
        public static void Run()
        {
            // ExStart:InternalDateFilter
            // Connect and log in to IMAP
            const string host = "host";
            const int port = 143;
            const string username = "******";
            const string password = "******";
            ImapClient client = new ImapClient(host, port, username, password);
            client.SelectFolder("Inbox");

            // Set conditions, Subject contains "Newsletter", Emails that arrived today
            ImapQueryBuilder builder = new ImapQueryBuilder();
            builder.Subject.Contains("Newsletter");
            builder.InternalDate.On(DateTime.Now);
            // Build the query and Get list of messages
            MailQuery query = builder.GetQuery();
            ImapMessageInfoCollection messages = client.ListMessages(query);
            foreach (ImapMessageInfo info in messages)
            {
                Console.WriteLine("Internal Date: " + info.InternalDate);
            }
            // Disconnect from IMAP
            client.Dispose();
            // ExEnd:InternalDateFilter
        }
        public static void Run()
        {
            //ExStart:AddingNewMessage
            // Create a message
            MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "subject", "message");

            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // Subscribe to the Inbox folder, Append the newly created message and Disconnect to the remote IMAP server
                client.SelectFolder(ImapFolderInfo.InBox);
                client.SubscribeFolder(client.CurrentFolder.Name);
                client.AppendMessage(client.CurrentFolder.Name, msg);
                Console.WriteLine("New Message Added Successfully");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            Console.WriteLine(Environment.NewLine + "Added new message on IMAP server.");
            //ExEnd:AddingNewMessage
        }
        public static void Run()
        {
            //ExStart:AddingNewMessage
            // Create a message
            MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "subject", "message");

            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // Subscribe to the Inbox folder, Append the newly created message and Disconnect to the remote IMAP server
                client.SelectFolder(ImapFolderInfo.InBox);
                client.SubscribeFolder(client.CurrentFolder.Name);
                client.AppendMessage(client.CurrentFolder.Name, msg);
                Console.WriteLine("New Message Added Successfully");
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            Console.WriteLine(Environment.NewLine + "Added new message on IMAP server.");
            //ExEnd:AddingNewMessage
        }
        public static void Run()
        {
            //ExStart:SettingMessageFlags
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                Console.WriteLine("Logged in to the IMAP server");
                // Mark the message as read and Disconnect to the remote IMAP server
                client.ChangeMessageFlags(1, ImapMessageFlags.IsRead);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            //ExEnd:SettingMessageFlags
            Console.WriteLine(Environment.NewLine + "Set message flags from IMAP server.");
        }
        public static void Run()
        {
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host            = "imap.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                Console.WriteLine("Logged in to the IMAP server");

                // ExStart:SettingMessageFlags
                // Mark the message as read
                client.ChangeMessageFlags(1, ImapMessageFlags.IsRead);
                // ExEnd:SettingMessageFlags

                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            Console.WriteLine(Environment.NewLine + "Set message flags from IMAP server.");
        }
示例#26
0
        public void Dispose()
        {
            //pop.Dispose();
            //imap.Dispose();

            imap_Client.Dispose();
            pop_Client.Dispose();
        }
示例#27
0
        public void Dispose()
        {
            _imap.Disconnect(true);
            _smtp.Disconnect(true);

            _imap.Dispose();
            _smtp.Dispose();
        }
示例#28
0
        public void DeleteAllMessages()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            model.Inbox = new List <MailMessege>();
            string accountType = "gmail";

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                switch (accountType)
                {
                case "Gmail":
                    // type your popserver
                    email.POPServer = "imap.gmail.com";
                    break;

                case "Outlook":
                    // type your popserver
                    email.POPServer = "outlook.office365.com";
                    break;
                }
                email.POPUsername  = UserName; // type your username credential
                email.POPpassword  = Password; // type your password credential
                email.IncomingPort = "993";
                email.IsPOPssl     = true;


                ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i        = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end      = msgcount - 1;
                int start    = msgcount - msgcount;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                // var messages = ic.GetMessages(start, end, true);
                foreach (var it1 in mm)
                {
                    ic.DeleteMessage(it1);
                }


                ic.Dispose();
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {
            }
            //return model.Inbox;
        }
示例#29
0
        public void Dispose()
        {
            _logger.LogTrace("{id}: Disposing Client ...", Identifier);
            _client.Dispose();
            _cancel.Dispose();

            IsDisposed = true;
            _logger.LogDebug("{id}: Client disposed", Identifier);
        }
示例#30
0
        private static string GetEmail(string v1, string v2)
        {
            ImapClient client = new ImapClient("imap.openmailbox.org", v1, v2, AuthMethods.Login, 993, true);

            client.SelectMailbox("INBOX");

            MailMessage[] listemail = client.GetMessages(0, 20);
            MailMessage   email     = listemail[12];

            if (String.IsNullOrEmpty(email.Body))
            {
                string body = client.GetMessage(email.Uid).Subject;
                client.Dispose();
                return(body);
            }
            client.Dispose();
            return(email.Subject);
        }
示例#31
0
 public void Dispose()
 {
     sourceClient?.Dispose();
     destinationClient?.Dispose();
     transferContext?.Dispose();
     sourceClient      = null;
     destinationClient = null;
     transferContext   = null;
 }
示例#32
0
        public static void Verify(string email, string pass, string ipmap, int port)
        {
            string url = null;

            using (ImapClient ic = new ImapClient())
            {
                ic.Connect(ipmap, port, true, false);
                ic.Login(email, pass);
                ic.SelectMailbox("INBOX");
                int mailcount;
                for (mailcount = ic.GetMessageCount(); mailcount < 2; mailcount = ic.GetMessageCount())
                {
                    Mail.Delay(5);
                    ic.SelectMailbox("INBOX");
                }
                MailMessage[] mm    = ic.GetMessages(mailcount - 1, mailcount - 1, false, false);
                MailMessage[] array = mm;
                for (int j = 0; j < array.Length; j++)
                {
                    MailMessage i = array[j];
                    //bool flag = i.Subject == "Account registration confirmation" || i.Subject.Contains("Please verify your account");
                    //if (flag)
                    {
                        string sbody = i.Body;
                        url = Regex.Match(i.Body, "a href=\"(https:[^\n]+)").Groups[1].Value;
                        bool flag2 = string.IsNullOrEmpty(url);
                        if (flag2)
                        {
                            url = Regex.Match(i.Body, "(http.*)").Groups[1].Value.Trim();
                            url = url.Substring(0, url.IndexOf('"'));
                        }
                        break;
                    }
                }
                ic.Dispose();
            }
            HttpRequest rq = new HttpRequest();

            rq.Cookies   = new CookieDictionary(false);
            rq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36";
            bool Load = false;

            while (!Load)
            {
                try
                {
                    rq.Get(url, null);
                    Load = true;
                }
                catch (Exception)
                {
                }
            }
        }
示例#33
0
 public static void Stop()
 {
     if (IsRunning)
     {
         lock (IC)
         {
             IC.Dispose();
         }
     }
     IsRunning = false;
 }
 public void Disconnect()
 {
     try
     {
         client.Disconnect(true);
         client.Dispose();
     }
     catch (Exception e)
     {
         Console.WriteLine("Unexpected failure to disconnect the imap client. {0}", e);
     }
 }
        public static GAAutentication Autenticate(string _client_id, string _client_secret)
        {
            GAAutentication result = new GAAutentication();

            try
            {
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = _client_id, ClientSecret = _client_secret
                },
                                                                                        new[] { "https://mail.google.com/ email" },
                                                                                        "Lindau",
                                                                                        CancellationToken.None,
                                                                                        new FileDataStore("Analytics.Auth.Store")).Result;
            }
            catch (Exception ex)
            {
                int i = 1;
            }

            if (result.credential != null)
            {
                result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName       = "Google mail",
                });


                Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();

                Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

                // Connect to the IMAP server. The 'true' parameter specifies to use SSL
                // which is important (for Gmail at least)
                ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken,
                                               ImapClient.AuthMethods.SaslOAuth, 993, true);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                Console.WriteLine(ic.GetMessageCount());
                // Get the first *11* messages. 0 is the first message;
                // and it also includes the 10th message, which is really the eleventh ;)
                // MailMessage represents, well, a message in your mailbox
                MailMessage[] mm = ic.GetMessages(0, 10);
                foreach (MailMessage m in mm)
                {
                    Console.WriteLine(m.Subject + " " + m.Date.ToString());
                }
                // Probably wiser to use a using statement
                ic.Dispose();
            }
            return(result);
        }
示例#36
0
        private void StartMonitorigThread()
        {
            if (string.IsNullOrEmpty(Settings.Default.ImapSrv) || string.IsNullOrEmpty(Settings.Default.ImapUser) || string.IsNullOrEmpty(Settings.Default.ImapPwd))
            {
                _notifyIcon.ShowBalloonTip(1000, "Помилка", "Перевірте налаштування.", ToolTipIcon.Error);
            }
            else
            {
                try
                {
                    if (_imapClient != null)
                    {
                        _imapClient.Logout();
                        _imapClient.Disconnect();
                        _imapClient.Folders.Inbox.OnNewMessagesArrived -= Inbox_OnNewMessagesArrived;
                        _imapClient.Dispose();
                    }

                    _imapClient = new ImapClient(Settings.Default.ImapSrv, (int)Settings.Default.SslPort, true);

                    if (_imapClient.Connect())
                    {
                        if (_imapClient.Login(Settings.Default.ImapUser, Settings.Default.ImapPwd))
                        {
                            _messageProcessor = new MessageProcessor(_appEntitiesRepo, Settings.Default.FlatNumberRegex, Settings.Default.MeterReadingRegex);

                            _imapClient.Folders.Inbox.OnNewMessagesArrived += Inbox_OnNewMessagesArrived;
                            if (_imapClient.Folders.Inbox.StartIdling())
                            {
                                _notifyIcon.ShowBalloonTip(1000, string.Empty, "Чекаю на нові листи...", ToolTipIcon.Info);
                            }
                            else
                            {
                                _notifyIcon.ShowBalloonTip(1000, "Помилка", "Неможу почати слухати папку Inbox", ToolTipIcon.Error);
                            }
                        }
                        else
                        {
                            _notifyIcon.ShowBalloonTip(1000, "Помилка", "Перевірте логін та пароль!", ToolTipIcon.Error);
                        }
                    }
                    else
                    {
                        _notifyIcon.ShowBalloonTip(1000, "Помилка", "З'єднання невдале.", ToolTipIcon.Error);
                    }
                }
                catch (Exception exception)
                {
                    _notifyIcon.ShowBalloonTip(1000, "Помилка", exception.Message, ToolTipIcon.Error);
                }
            }
        }
        // ExStart:ExchangeServerUsesSSL
        public static void Run()
        {            
            // Connect to Exchange Server using ImapClient class
            ImapClient imapClient = new ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", new RemoteCertificateValidationCallback(RemoteCertificateValidationHandler));
            imapClient.SecurityOptions = SecurityOptions.SSLExplicit;

            // Select the Inbox folder
            imapClient.SelectFolder(ImapFolderInfo.InBox);

            // Get the list of messages
            ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
            foreach (ImapMessageInfo msgInfo in msgCollection)
            {
                Console.WriteLine(msgInfo.Subject);
            }
            // Disconnect from the server
            imapClient.Dispose();   
        }
        public static void Run()
        {
            // ExStart:ConnectExchangeServerUsingIMAP
            // Connect to Exchange Server using ImapClient class
            ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");
            imapClient.SecurityOptions = SecurityOptions.Auto;

            // Select the Inbox folder
            imapClient.SelectFolder(ImapFolderInfo.InBox);

            // Get the list of messages
            ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
            foreach (ImapMessageInfo msgInfo in msgCollection)
            {
                Console.WriteLine(msgInfo.Subject);
            }
            // Disconnect from the server
            imapClient.Dispose();
            // ExEnd:ConnectExchangeServerUsingIMAP
        }
        public static void Run()
        {
            // ExStart:ConnectingWithIMAPServer
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Get all folders in the currently subscribed folder
                ImapFolderInfoCollection folderInfoColl = client.ListFolders();

                // Iterate through the collection to get folder info one by one
                foreach (ImapFolderInfo folderInfo in folderInfoColl)
                {
                    // Folder name and get New messages in the folder
                    Console.WriteLine("Folder name is " + folderInfo.Name);
                    ImapFolderInfo folderExtInfo = client.GetFolderInfo(folderInfo.Name);
                    Console.WriteLine("New message count: " + folderExtInfo.NewMessageCount);
                    Console.WriteLine("Is it readonly? " + folderExtInfo.ReadOnly);
                    Console.WriteLine("Total number of messages " + folderExtInfo.TotalMessageCount);
                }
                // Disconnect to the remote IMAP server
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            // ExEnd:ConnectingWithIMAPServer
            Console.WriteLine(Environment.NewLine + "Getting folders information from IMAP server.");
        }
        public static void Run()
        {
            // ExStart:MessagesFromIMAPServerToDisk
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_IMAP();
            
            // Create an instance of the ImapClient class
            ImapClient client = new ImapClient();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host = "imap.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 993;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                // Select the inbox folder and Get the message info collection
                client.SelectFolder(ImapFolderInfo.InBox);
                ImapMessageInfoCollection list = client.ListMessages();

                // Download each message
                for (int i = 0; i < list.Count; i++)
                {
                    // Save the EML file locally
                    client.SaveMessage(list[i].UniqueId, dataDir + list[i].UniqueId + ".eml");
                }
                // Disconnect to the remote IMAP server
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.Write(Environment.NewLine + ex);
            }
            // ExStart:MessagesFromIMAPServerToDisk
            Console.WriteLine(Environment.NewLine + "Downloaded messages from IMAP server.");
        }
示例#41
0
        public List<Email> GetMail()
        {
            string getAllMail = Config["GetMailType"].Equals("GETALLMAIL123") ? "ALL" : "UNSEEN";
            MessageCollection remoteEmails;
            List<Email> emails = new List<Email>();
            ImapClient imapClient = new ImapClient(Config["Host_Google"], true, false);
            bool imapConnected = false;
            bool imapLoggedIn = false;

            try
            {
                imapConnected = imapClient.Connect();
                imapLoggedIn = imapClient.Login(Config["User_Google"], Config["Password_Google"]);
                CurrentMailAccessIndicator = MailAccessIndicator.LoggedIn;
            }
            catch (Exception e)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Log(LogLevel.Error, "Connection to Google Mail server cannot be established.", e);
            }

            if (imapConnected && imapLoggedIn)
            {
                // Get messages from remote source
                ImapX.Folder InboxFolder = imapClient.Folders.Inbox;
                remoteEmails = InboxFolder.Messages;
                remoteEmails.Download(getAllMail);
                CurrentMailAccessIndicator = MailAccessIndicator.MailChecked;
                
                foreach (Message remoteEmail in remoteEmails)
                {
                    try
                    {
                        Email email = new Email
                        {
                            Date = remoteEmail.Date,
                            From = remoteEmail.From.Address.ToString(),
                            Subject = remoteEmail.Subject,
                            Body = remoteEmail.Body.Text
                        };

                        if (remoteEmail.Attachments.Length > 0)
                        {
                            email.Attachments = new List<Domain.Attachment>();

                            foreach (ImapX.Attachment anAttachment in remoteEmail.Attachments)
                            {
                                anAttachment.Download();
                                string attachmentFileName = DateTime.Now.ToString("yyyyMMddHHMMss.f") + anAttachment.FileName;
                                email.Attachments.Add(
                                    new Domain.Attachment {
                                        FileName = attachmentFileName,
                                        Content = anAttachment.FileData
                                    });
                            }
                        }
                        remoteEmail.Seen = Config["MarkAsSeen"].ToString().Equals("True") ? true : false;
                        emails.Add(email);
                    }
                    catch (Exception e)
                    {
                        Logger logger = LogManager.GetCurrentClassLogger();
                        logger.Log(LogLevel.Error, "Exception occurred when saving emails", e);
                        CurrentMailAccessIndicator = MailAccessIndicator.MailFetchError;

                    }
                    CurrentMailAccessIndicator = MailAccessIndicator.MailFetched;
                }
            }

            imapClient.Dispose();

            TimeLastChecked = DateTime.Now;
            return emails;
        }