Пример #1
1
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            using (Pop3Client client = new Pop3Client())
            {
                //Para conectar no servidor do gmail use a porta 995 e SSL
                client.Connect("pop.gmail.com", 995, true);
                //Para conectar no servidor do hotmail use a porta 995 e SSL
                //client.Connect("pop3.live.com", 995, true);
                //usuário e senha para autenticar
                client.Authenticate("luisfelipe.lambert", "sakuda5G");
                //Pega o número de mensagens
                int messageCount = client.GetMessageCount();

                //Instanciar a lista 
                List<Message> mensagens = new List<Message>();
                //Pegar as mensagens
                for (int i = messageCount; i > 0; i--)
                {
                    //Adicionar a mensagem a lista
                    mensagens.Add(client.GetMessage(i));
                }
                //Popular o repeater com as mensagens
                repMensagens.DataSource = mensagens;
                repMensagens.DataBind();
            }
        }
        catch (Exception ex)
        {
            //Caso ocorra algum erro, uma mensagem será exibida na página
            litMensagemErro.Text = ex.ToString();
        }
    }
Пример #2
0
 public static Pop3Client InstancePOP3Client()
 {
     #region CuongPV old -- HaiHM Modify 8/4/2019
     #endregion
     if (EmailConf == null)
     {
         EmailConf = db.TblEmailConfigs.FirstOrDefault();
     }
     pop3Client = new Pop3Client();
     try
     {
         pop3Client.ServerCertificateValidationCallback = (s, c, h, e) => true;
         pop3Client.AuthenticationMechanisms.Remove(OrganizationConstant.Remove);
         if (EmailConf.IsDeleted.HasValue && EmailConf.IsDeleted.HasValue)
         {
             pop3Client.Connect(EmailConf.ServerGet, Convert.ToInt32(EmailConf.PortGet), SecureSocketOptions.SslOnConnect);
         }
         else
         {
             pop3Client.Connect(EmailConf.ServerGet, Convert.ToInt32(EmailConf.PortGet), SecureSocketOptions.Auto);
         }
         pop3Client.Authenticate(EmailConf.UserName, EmailConf.Password);
     }
     catch (Exception e)
     {
         throw e;
     }
     return(pop3Client);
 }
        public void TestConnectWorks()
        {
            Stream inputStream  = new MemoryStream(Encoding.ASCII.GetBytes("+OK"));            // Welcome message
            Stream outputStream = new MemoryStream();

            Assert.DoesNotThrow(delegate { Client.Connect(new CombinedStream(inputStream, outputStream)); });
        }
        /// <summary>
        /// Let the <see cref="Pop3Client"/> connect.
        /// </summary>
        /// <param name="extraReaderInput">Extra input that the server may read off the reader. String is convert to bytes using ASCII encoding</param>
        private void Connect(string extraReaderInput = "")
        {
            string readerInput  = "+OK\r\n" + extraReaderInput;            // Always allow connect, which is the first ok
            Stream inputStream  = new MemoryStream(Encoding.ASCII.GetBytes(readerInput));
            Stream outputStream = new MemoryStream();

            // Connect with the client
            Client.Connect(new CombinedStream(inputStream, outputStream));
        }
Пример #5
0
 public bool Connect(string host, int port, string type)
 {
     if (_proxyClient != null)
     {
         _pop3Client.Connect(_proxyClient.CreateConnection(host, port), host, port, type == "SSL");
         return(_pop3Client.IsConnected);
     }
     _pop3Client.Connect(host, port, type == "SSL");
     return(_pop3Client.IsConnected);
 }
Пример #6
0
        public void TestArgumentExceptions()
        {
            using (var client = new Pop3Client()) {
                var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

                // Connect
                Assert.Throws <ArgumentNullException> (() => client.Connect((Uri)null));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync((Uri)null));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 110, false));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 110, false));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 110, false));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 110, false));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, false));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, false));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, SecureSocketOptions.None));

                Assert.Throws <ArgumentNullException> (() => client.Connect(null, "host", 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(socket, "host", 110, SecureSocketOptions.None));

                // Authenticate
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, "password"));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, "password"));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate("username", null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync("username", null));
            }
        }
Пример #7
0
        public void ConnectAlreadyConnect()
        {
            Pop3Client pop3Client = new Pop3Client(new PlainMessagesDummyNetworkOperations());

            Assert.IsFalse(pop3Client.IsConnected);

            pop3Client.Connect("SERVER", "USERNAME", "PASSWORD", true);
            Assert.IsTrue(pop3Client.IsConnected);

            pop3Client.Connect("SERVER", "USERNAME", "PASSWORD", 995, true);
        }
Пример #8
0
        /// <summary>
        /// Let the <see cref="Pop3Client"/> authenticate.
        /// </summary>
        /// <param name="extraReaderInput">Extra input that the server may read off the reader.  String is convert to bytes using ASCII encoding</param>
        private void Authenticate(string extraReaderInput = "")
        {
            // Always allow connect, which is the first ok
            // And always allow authenticate
            string readerInput  = "+OK\r\n+OK\r\n+OK\r\n" + extraReaderInput;
            Stream inputStream  = new MemoryStream(Encoding.ASCII.GetBytes(readerInput));
            Stream outputStream = new MemoryStream();

            // Authenticate with the client
            Client.Connect(new CombinedStream(inputStream, outputStream));
            Client.Authenticate(RandomString, RandomString);
        }
Пример #9
0
        public void LoginForm_PasswordRestoreWithValidEmail()
        {
            using (IWebDriver driver = new FirefoxDriver())
            {
                driver.Navigate().GoToUrl(gg);

                //Открытие формы
                IWebElement formLink = driver.FindElement(By.XPath(@"//*[@id=""top_back""]/div[3]/a[1]"));
                formLink.Click();

                WebDriverWait wait        = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                IWebElement   overlay     = driver.FindElement(By.Id("cboxOverlay"));
                IWebElement   colorbox    = driver.FindElement(By.Id("colorbox"));
                IWebElement   messageBox  = driver.FindElement(By.ClassName("status-error"));
                IWebElement   emailField  = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Email")));
                IWebElement   restoreLink = wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Я не помню пароль")));

                Assert.IsTrue(colorbox.Displayed, "Форма не открылась");

                emailField.SendKeys(validEmail);
                restoreLink.Click();
                try { wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("status-message"), "Инструкция по восстановлению отправлена")); }
                catch (Exception e) { Assert.Fail("Не появилось сообщение об отправке письма"); }
            }
            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);
                client.Authenticate(validEmail, emailPass);

                int messageNumber = client.GetMessageCount();
                int i             = 0;
                while (messageNumber == 0 && i < 60)
                {
                    client.Disconnect();
                    System.Threading.Thread.Sleep(5000);
                    client.Connect(hostname, port, useSsl);
                    client.Authenticate(validEmail, emailPass);
                    messageNumber = client.GetMessageCount();
                    i             = i++;
                }

                Assert.IsTrue(messageNumber > 0, "Письмо не пришло");

                MessageHeader  headers = client.GetMessageHeaders(messageNumber);
                RfcMailAddress from    = headers.From;
                string         subject = headers.Subject;
                client.DeleteAllMessages();

                Assert.IsFalse(from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Восстановление пароля на Gama - Gama".Equals(subject), "Письмо не пришло");
            }
        }
Пример #10
0
        /// <summary>
        /// gets all unread email from Gmail and returns a List of System.Net.Email.MailMessage Objects
        /// </summary>
        /// <param name="username">Gmail Login</param>
        /// <param name="password">mail Password</param>
        public static List <MailMessage> FetchAllUnreadMessages(string username, string password)
        {
            List <MailMessage> mlist = new List <MailMessage>();

            // The client disconnects from the server when being disposed

            try
            {
                using (Pop3Client client = new Pop3Client())
                {
                    // Connect to the server
                    client.Connect("pop.gmail.com", 995, true);

                    // Authenticate ourselves towards the server
                    client.Authenticate(username, password);

                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();



                    for (int x = messageCount; x > 0; x--)
                    {
                        Message m = new Message(client.GetMessage(x).RawMessage);
                        System.Net.Mail.MailMessage mm = m.ToMailMessage();

                        mlist.Add(mm);
                    }
                    return(mlist);
                }
            }
            catch { return(mlist); }
        }
Пример #11
0
        public List <EmailMessage> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                emailClient.Connect(_emailConfiguration.PopServer, _emailConfiguration.PopPort, true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate(_emailConfiguration.PopUsername, _emailConfiguration.PopPassword);

                List <EmailMessage> emails = new List <EmailMessage>();
                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new EmailMessage
                    {
                        Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject
                    };
                    emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                }

                return(emails);
            }
        }
Пример #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a POP3 client
            Pop3Client pop = new Pop3Client();

            //Set host, username, password etc. for the client
            pop.Host      = "pop.chemitec.it";
            pop.Username  = "******";
            pop.Password  = "******";
            pop.Port      = 995;
            pop.EnableSsl = true;

            //Connect the server
            pop.Connect();
            //Get the first message by its sequence number
            Pop3MessageInfoCollection m = pop.GetAllMessages();
            MailMessage message         = pop.GetMessage(54);

            //Parse the message
            message.Save("Sample.msg", MailMessageFormat.Msg);

            Console.WriteLine("------------------ HEADERS ---------------");
            Console.WriteLine("From : " + message.From.ToString());
            Console.WriteLine("To : " + message.To.ToString());
            Console.WriteLine("Date : " + message.Date.ToString(CultureInfo.InvariantCulture));
            Console.WriteLine("Subject: " + message.Subject);
            Console.WriteLine("------------------- BODY -----------------");
            Console.WriteLine(message.BodyText);
            Console.WriteLine("------------------- END ------------------");
            //Save the message to disk using its subject as file name
            message.Save(message.Subject + ".eml", MailMessageFormat.Eml);
            Console.WriteLine("Message Saved.");
        }
Пример #13
0
        public IEnumerable <MailMessage> Retrieve(string pMailAddress, string pPassword, int pOffset = 0, int pWindow = 0)
        {
            try
            {
                if (pWindow == 0)
                {
                    return(new List <MailMessage>());
                }

                Pop3Client mPop3Client = new Pop3Client();
                mPop3Client.Connect(this.iProtocol.Host, this.iProtocol.Port, this.iProtocol.SSL);
                mPop3Client.Authenticate(pMailAddress, pPassword);

                if (pWindow > mPop3Client.GetMessageCount() || pWindow == -1)
                {
                    pWindow = mPop3Client.GetMessageCount();
                }

                return(mPop3Client.GetMessageCount() > 0 ?
                       Enumerable.Range(pOffset + 1, pWindow)
                       .Select(bIndex => this.ProjectToMailMessage(mPop3Client.GetMessage(bIndex)))
                       .ToList()
                    : new List <MailMessage>());
            }
            catch (Exception bException)
            {
                throw new FailOnRetrieve("Error en Pop3, posible problema con la conexión, autenticación o recupero de correos. Vea excepción interna.", bException);
            }
        }
Пример #14
0
        public List <EmailMessage> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                emailClient.Connect("pop.gmail.com", 995, true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate("*****@*****.**", "");

                var emails = new List <EmailMessage>();
                for (var i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new EmailMessage
                    {
                        Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject
                    };
                    emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                }

                return(emails);
            }
        }
Пример #15
0
 /// <summary>
 /// Used to connect client to server.
 /// </summary>
 private bool Connect()
 {
     client = new Pop3Client();
     try
     {
         client.Connect(Pop3, Port, UseSsl);
         try
         {
             client.Authenticate(Client_Mail.ToString(), Password.ToString(), AuthenticationMethod.Auto);
             client.NoOperation();
             ThreadStart processTaskThread = delegate
             {
                 dispatcherTimer.Tick    += new EventHandler(dispatcherTimer_Tick);
                 dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                 dispatcherTimer.Start();
             };
             Thread thread = new Thread(processTaskThread);
             thread.Start();
             return(true);
         }
         catch {
             // user authentication error
             MessageBox.Show("User authentication error.", "error");
         }
     }
     catch {
         // POP3 connection error
         MessageBox.Show("POP3 connection error.", "error");
     }
     return(false);
 }
Пример #16
0
        // -----------------------------------------------------------   / fim xml   ------------------------------------------------

        // deletar por id
        public bool DeleteMessageByMessageId(string messageId)
        {
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages on the POP3 server
                int messageCount = client.GetMessageCount();

                // Run trough each of these messages and download the headers
                for (int messageItem = messageCount; messageItem > 0; messageItem--)
                {
                    // If the Message ID of the current message is the same as the parameter given, delete that message
                    if (client.GetMessageHeaders(messageItem).MessageId == messageId)
                    {
                        // Delete
                        client.DeleteMessage(messageItem);
                        return(true);
                    }
                }
            }
            // We did not find any message with the given messageId, report this back
            return(false);
        }
    protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";

        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = txtPassword.Text;

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>";

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
Пример #18
0
        /// <summary>
        /// 下载邮件附件
        /// </summary>
        /// <param name="path">下载路径</param>
        /// <param name="messageId">邮件编号</param>
        public (bool, string) DownAttachmentsById(string path, int messageId)
        {
            var zipFilePath = "";

            using (Pop3Client client = new Pop3Client())
            {
                try
                {
                    if (client.Connected)
                    {
                        client.Disconnect();
                    }
                    client.Connect(popServer, popPort, isUseSSL);
                    client.Authenticate(accout, pass);
                    Message  message  = client.GetMessage(messageId);
                    string   senders  = message.Headers.From.DisplayName;
                    string   from     = message.Headers.From.Address;
                    string   subject  = message.Headers.Subject;
                    DateTime Datesent = message.Headers.DateSent;


                    List <MessagePart> messageParts = message.FindAllAttachments();

                    if (messageParts.Count == 0)
                    {
                        return(false, zipFilePath);
                    }


                    foreach (var item in messageParts)
                    {
                        if (item.IsAttachment)
                        {
                            if (item.FileName.Contains(".z"))
                            {
                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                }
                                var filePath = System.IO.Path.Combine(path, item.FileName);

                                File.WriteAllBytes(filePath, item.Body);

                                if (item.FileName.Contains(".zip"))
                                {
                                    zipFilePath = filePath;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取附件出错:" + ex.Message);
                    return(false, zipFilePath);
                }
            }

            return(true, zipFilePath);
        }
Пример #19
0
 public bool TestConnection(string server, int port, bool use_ssl, string username, string password)
 {
     try
     {
         if (pop3Client.Connected)
         {
             pop3Client.Disconnect();
         }
         pop3Client.Connect(server, port, use_ssl);
         pop3Client.Authenticate(username, password);
         return(true);
     }
     catch (InvalidLoginException)
     {
         MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
     }
     catch (PopServerNotFoundException)
     {
         MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
     }
     catch (PopServerLockedException)
     {
         MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
     }
     catch (LoginDelayException)
     {
         MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
     }
     catch (Exception e)
     {
         MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
     }
     return(false);
 }
Пример #20
0
        /// <summary>
        /// POP3接收邮件
        /// </summary>
        /// <param name="FromAccount">邮箱账户</param>
        /// <param name="FromPassword">邮箱密码</param>
        /// <returns></returns>
        public static IList <ReceiveEmailModel> ReceivePop3Email(string FromAccount, string FromPassword)
        {
            List <ReceiveEmailModel> receiveEmailList = new List <ReceiveEmailModel>();

            using (var client = new Pop3Client())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(PopServer, PopPort, false);

                client.Authenticate(FromAccount, FromPassword);

                for (int i = 0; i < client.Count; i++)
                {
                    var message = client.GetMessage(i);

                    ReceiveEmailModel receiveEmailModel = new ReceiveEmailModel();

                    receiveEmailModel.FromAddress = message.From[0].Name;

                    receiveEmailModel.Date = message.Date.DateTime;

                    receiveEmailModel.Subject = message.Subject;

                    receiveEmailModel.Body = message.TextBody;

                    receiveEmailList.Add(receiveEmailModel);
                }
                client.Disconnect(true);
            }
            return(receiveEmailList);
        }
        private static void FetchMessages(string host, int port, bool ssl, string username, string password)
        {
            //3rd party Pop3 library
            using (Pop3Client client = new Pop3Client())
            {
                //Connect and authenticate to Pop3 specifying our own certificate validator function to bypass self signed certificate
                client.Connect(host, port, ssl, 5000, 5000, certificateValidator: certificateValidator);
                client.Authenticate(username, password);

                //Get number of messages in the inbox
                int messageCount = client.GetMessageCount();

                //Create List of type Message to hold the messages
                List <Message> allMessages = new List <Message>(messageCount);
                if (messageCount == 0)
                {
                    //If there are no messages
                    Console.WriteLine("No messages in inbox");
                }
                for (int i = messageCount; i > 0; i--)
                {
                    //For every message add it to our List
                    allMessages.Add(client.GetMessage(i));
                }

                foreach (Message message in allMessages)
                {
                    //For every message in our list convert it to a .NET MailMessage and print the Subject
                    Console.WriteLine("Found Message:" + message.ToMailMessage().Subject);
                }
            }
        }
Пример #22
0
        public void Run(Action <string> log)
        {
            LogLine = log;
            SocketTraceListener.Start();
            var  ui             = Dispatcher.CurrentDispatcher;
            uint numberOfEmails = 0;

            Task.Run(() =>
            {
                try
                {
                    var client = new Pop3Client();
                    client.Connect(Server, Port, SSL);
                    client.SendAuthUserPass(Username, Password);

                    numberOfEmails = client.GetEmailCount();
                    client.Disconnect();
                }
                catch (Exception ex)
                {
                    ui.Invoke(delegate { LogLine($"### {ex.Message}"); });
                }

                ui.Invoke(delegate
                {
                    Log($"### {numberOfEmails} Messages.");
                    LogLine("### DIAGNOSTICS TRACE START");
                    Log(SocketTraceListener.Stop());
                    LogLine("### DIAGNOSTICS TRACE END");
                });
            });
        }
Пример #23
0
        public List <Message> GetMessages(string password)
        {
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(SMTPServer, 110, false);

                // Authenticate ourselves towards the server
                client.Authenticate(_username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List <Message> allMessages = new List <Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number

                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                // Now return the fetched messages
                return(allMessages);
            }
        }
Пример #24
0
        public string GetLastMail(AccountData account)//читаем последнее письмо и возвращаем текст
        {
            for (int i = 0; i < 30; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, account.Name, account.Password, false);
                pop3.Connect();
                pop3.Authenticate();

                if (pop3.GetMessageCount() > 0)
                {
                    MailMessage message = pop3.GetMessage(1);
                    //ReadOnlyMailMessage message = pop3.GetMessage(1); //устарело!!

                    string body = message.Body;
                    pop3.DeleteMessage(1);
                    pop3.LogOut();
                    return(message.Body);
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                }
            }

            return(null); //Если цикл завершился возвращаем ничего - письмо так и не пришло
        }
Пример #25
0
        public void TestMethod1()
        {
            /*AccountData account = new AccountData()
             * {
             *  Name = "user",
             *  Password = "******"
             * };
             * Assert.IsFalse(app.James.Verify(account));
             * app.James.Add(account);
             * Assert.IsTrue(app.James.Verify(account));
             * app.James.Delete(account);
             * Assert.False(app.James.Verify(account));*/

            for (int i = 0; i < 20; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, "user1", "password", false);
                pop3.Connect();
                pop3.Authenticate();
                if (pop3.GetMessageCount() > 0)
                {
                    ReadOnlyMailMessage message = pop3.GetMessage(1);
                    string body = message.Body;
                    pop3.DeleteMessage(1);
                    System.Console.Out.WriteLine(body);
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                }
            }
        }
Пример #26
0
        //public List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        public List <Message> FetchAllMessages()
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(PopServerHost, port, true);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List <OpenPop.Mime.Message> allMessages = new List <OpenPop.Mime.Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                client.Disconnect();

                // Now return the fetched messages
                return(allMessages);
            }
        }
        /// <summary>
        /// The receive mess.
        /// </summary>
        public static void ReceiveMess(IReceivingManager receivingManager, ILogger logger)
        {
            string mailServer   = ConfigurationManager.AppSettings["MailServer"];
            int    mailPort     = Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"]);
            string mailLogin    = ConfigurationManager.AppSettings["MailLogin"];
            string mailPassword = Encoding.Unicode.GetString(Convert.FromBase64String(ConfigurationManager.AppSettings["MailPassword"]));

            var client = new Pop3Client();

            try
            {
                client.Connect(mailServer, mailPort, false);
                client.Authenticate(mailLogin, mailPassword);

                List <Header> msgs = GetMsgsForSB(client);
                foreach (Header header in msgs)
                {
                    if (!header.stored)
                    {
                        if (header.msg.Headers.Subject.Contains("OUT_OF"))
                        {
                            Header        tmpHeader = header;
                            List <Header> curMsgs   =
                                msgs.Where(
                                    msg => msg.msg.Headers.Subject.Contains(tmpHeader.msg.Headers.Subject.Split('_')[4]))
                                .ToList();

                            if (curMsgs.Count() == Convert.ToInt32(header.msg.Headers.Subject.Split('_')[8]))
                            {
                                SaveMsgToDBFromManyAttachs(curMsgs, receivingManager);

                                foreach (Header msg in curMsgs)
                                {
                                    msg.stored = true;
                                }
                            }
                        }
                        else
                        {
                            SaveMsgToDB(header.msg, header.msg.Headers.Subject.Split('_')[4], receivingManager);

                            header.stored = true;
                        }
                    }
                }

                DeleteStoredMessages(client, msgs);
            }
            catch (Exception e)
            {
                logger.LogUnhandledException(e);
            }
            finally
            {
                if (client.Connected)
                {
                    client.Disconnect();
                }
            }
        }
Пример #28
0
        public List <EmailMessage> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                // 995 is for POP3 server port, this might change from one server to another.
                // SecureSocketOptions.Auto for SSL.
                emailClient.Connect("POP3 server name", 995, SecureSocketOptions.Auto);

                //Remove any OAuth functionality as we won't be using it.
                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate("POP3 server username", "POP3 server password");
                List <EmailMessage> emails = new List <EmailMessage>();
                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    // i variable is for maximum number of messages to retrieve
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new EmailMessage
                    {
                        Content     = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject     = message.Subject,
                        SenderName  = message.Sender.Name,
                        SenderEmail = message.Sender.Address
                    };
                }

                return(emails);
            }
        }
Пример #29
0
        public void FetchMessages(string hostname, int port, bool useSsl, string username, string password, int lim = 0)
        {
            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);
                client.Authenticate(username, password, AuthenticationMethod.UsernameAndPassword);
                int messageCount = client.GetMessageCount();
                using (localDBEntities context = new localDBEntities())
                {
                    OpenPop.Mime.Message m;
                    for (int i = messageCount; i > 0; i--)
                    {
                        if (i <= messageCount - lim)
                        {
                            break;
                        }

                        //--------------------->
                        m = client.GetMessage(i);
                        var t = new message()
                        {
                            messageID    = m.Headers.MessageId,
                            sender       = m.Headers.From.DisplayName + " - <" + m.Headers.From.Address + ">",
                            subject      = m.Headers.Subject,
                            content_view = m.Headers.ContentDescription,
                            date         = m.Headers.DateSent.ToShortDateString(),
                            read         = false,
                            attachment   = m.FindAllAttachments().Count > 0 ? true : false
                        };
                        context.messages.Add(t);
                    }
                    context.SaveChanges();
                }
            }
        }
Пример #30
0
        public void RetrieveHeaderListOk()
        {
            Pop3Client pop3Client = new Pop3Client(new OnlyHeadersDummyNetworkOperations());

            pop3Client.Connect("SERVER", "USERNAME", "PASSWORD");

            List <Pop3Message> messages = new List <Pop3Message>(pop3Client.List());

            pop3Client.RetrieveHeader(messages);
            Assert.IsFalse(messages[0].Retrieved);
            Assert.IsNotNull(messages[0].RawHeader);
            Assert.IsNull(messages[0].RawMessage);
            Assert.AreEqual("Rodolfo Finochietti <*****@*****.**>", messages[0].From);
            Assert.AreEqual("\"[email protected]\" <*****@*****.**>", messages[0].To);
            Assert.AreEqual("Tue, 13 Nov 2012 10:57:04 -0500", messages[0].Date);
            Assert.AreEqual("<*****@*****.**>", messages[0].MessageId);
            Assert.AreEqual("Test 1", messages[0].Subject);
            Assert.AreEqual("quoted-printable", messages[0].ContentTransferEncoding);
            Assert.IsNull(messages[0].Body);
            Assert.AreEqual("1.0", messages[0].GetHeaderData("MIME-Version"));
            Assert.AreEqual("Ac3Bt4nMDtM3y3FyQ1yd71JVtsSGJQ==", messages[0].GetHeaderData("Thread-Index"));
            Assert.IsFalse(messages[1].Retrieved);
            Assert.IsNotNull(messages[1].RawHeader);
            Assert.IsNull(messages[1].RawMessage);
            Assert.AreEqual("Rodolfo Finochietti <*****@*****.**>", messages[1].From);
            Assert.AreEqual("\"[email protected]\" <*****@*****.**>", messages[1].To);
            Assert.AreEqual("Tue, 13 Nov 2012 10:57:28 -0500", messages[1].Date);
            Assert.AreEqual("<*****@*****.**>", messages[1].MessageId);
            Assert.AreEqual("Test 2", messages[1].Subject);
            Assert.AreEqual("base64", messages[1].ContentTransferEncoding);
            Assert.IsNull(messages[1].Body);
            Assert.AreEqual("Microsoft-MacOutlook/14.2.4.120824", messages[1].GetHeaderData("user-agent:"));
            Assert.AreEqual(String.Empty, messages[1].GetHeaderData("X-MS-Has-Attach:"));
        }
Пример #31
0
        public static void DownloadNewMessages(HashSet <string> previouslyDownloadedUids)
        {
            using (var client = new Pop3Client()) {
                client.Connect("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

                client.Authenticate("username", "password");

                if (!client.Capabilities.HasFlag(Pop3Capabilities.UIDL))
                {
                    throw new Exception("The POP3 server does not support UIDs!");
                }

                var uids = client.GetMessageUids();

                for (int i = 0; i < client.Count; i++)
                {
                    // check that we haven't already downloaded this message
                    // in a previous session
                    if (previouslyDownloadedUids.Contains(uids[i]))
                    {
                        continue;
                    }

                    var message = client.GetMessage(i);

                    // write the message to a file
                    message.WriteTo(string.Format("{0}.msg", uids[i]));

                    // add the message uid to our list of downloaded uids
                    previouslyDownloadedUids.Add(uids[i]);
                }

                client.Disconnect(true);
            }
        }
Пример #32
0
        /// <summary>
        /// Example showing:
        ///  - how to fetch all messages from a POP3 server
        /// </summary>
        /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param>
        /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param>
        /// <param name="useSsl">Whether or not to use SSL to connect to server</param>
        /// <param name="username">Username of the user on the server</param>
        /// <param name="password">Password of the user on the server</param>
        /// <returns>All Messages on the POP3 server</returns>
        public static List <OPMessage> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List <OPMessage> allMessages = new List <OPMessage>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                for (int i = 1; i <= messageCount; i++)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                // Now return the fetched messages
                return(allMessages);
            }
        }
Пример #33
0
        public void ConnectOk( )
        {
            Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" );
            Assert.IsTrue( pop3Client.IsConnected );
        }
Пример #34
0
        public void ConnectFailNotResponse( )
        {
            Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( );

            Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" );
        }
    protected void gvMessages_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DisplayMessage")
        {
            pnlMessage.Visible = true;
            string msgSequenceNumber = e.CommandArgument.ToString();

            try
            {
                // initialize pop3 client
                Pop3Client client = new Pop3Client();
                client.Host = txtHost.Text;
                client.Port = int.Parse(txtPort.Text);
                client.Username = txtUsername.Text;
                client.Password = Session["Password"].ToString();

                // SSL settings
                if (chSSL.Checked == true)
                {
                    client.EnableSsl = true;
                    client.SecurityMode = Pop3SslSecurityMode.Implicit;
                }

                // connect to pop3 server and login
                client.Connect(true);
                lblMessage.ForeColor = Color.Green;
                lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>";

                // get the message
                MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber));
                // sender name and address
                litFrom.Text = msg.From[0].DisplayName + " <" + msg.From[0].Address + ">";
                // to addresses
                litTo.Text = "";
                foreach (MailAddress address in msg.To)
                {
                    litTo.Text += address.DisplayName + " <" + address.Address + "> , ";
                }
                // cc addresses
                litCc.Text = "";
                foreach (MailAddress address in msg.CC)
                {
                    litCc.Text += address.DisplayName + " <" + address.Address + "> , ";
                }
                // subject
                litSubject.Text = msg.Subject;
                litBody.Text = msg.HtmlBody;

                client.Disconnect();
            }
            catch (Exception ex)
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Error: " + ex.Message;
            }
        }
    }
Пример #36
0
        public void ConnectFail( )
        {
            Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( );
            mockNetworkOperations.Setup( no => no.Read( ) ).Returns( "-ERR" );

            Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", true );
        }
Пример #37
0
        public void ConnectAlreadyConnect( )
        {
            Pop3Client pop3Client = new Pop3Client( new FullMessagesDummyNetworkOperations( ) );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", true );
            Assert.IsTrue( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", 995, true );
        }
    private void DownloadFile(string msgSequenceNumber, string format)
    {
        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = Session["Password"].ToString();

            // SSL settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = Pop3SslSecurityMode.Implicit;
            }

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>";

            // get the message
            MemoryStream stream = new MemoryStream();
            MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber));
            if (format == "eml")
                msg.Save(stream, MessageFormat.Eml);
            else
                msg.Save(stream, MessageFormat.Msg);
            stream.Position = 0;
            byte[] msgBytes = new byte[stream.Length];
            stream.Read(msgBytes, 0, (int)stream.Length);

            client.Disconnect();

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("Content-Length", msgBytes.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=Message." + format);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(msgBytes);
            Response.End();

        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
    protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";

        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = txtPassword.Text;

            // SSL settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = Pop3SslSecurityMode.Implicit;
            }

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to SSL enabled POP3 Mail server.<br><hr>";

            // get mailbox information
            Pop3MailboxInfo mailboxInfo = client.GetMailboxInfo();
            long nMailboxSize = mailboxInfo.OccupiedSize;
            string strMailboxSize = "";

            // convert size in easy to read format
            if (nMailboxSize <= 1024)
                strMailboxSize = nMailboxSize.ToString() + " bytes";
            else if (nMailboxSize > 1024 && nMailboxSize <= (1024 * 1024))
                strMailboxSize = nMailboxSize.ToString() + " bytes (approx " + Math.Round((double)nMailboxSize / 1024, 2).ToString() + " KB)";
            else
                strMailboxSize = nMailboxSize.ToString() + " bytes (approx " + Math.Round((double)nMailboxSize / (1024 * 1024), 2).ToString() + " MB)";

            lblMailboxSize.Text = strMailboxSize;
            lblMessageCount.Text = mailboxInfo.MessageCount.ToString() + " messages found";

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
Пример #40
0
        public static void GetMessages( string server, string userName, string password, bool useSsl )
        {
            try
            {
                Pop3Client pop3Client = new Pop3Client( );

                Console.WriteLine( "Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine );

                pop3Client.Connect( server, userName, password, useSsl );

                Console.WriteLine( "List Messages...{0}", Environment.NewLine );

                IEnumerable<Pop3Message> messages = pop3Client.List( );

                Console.WriteLine( "Retrieve Messages...{0}", Environment.NewLine );

                foreach ( Pop3Message message in messages )
                {
                    Console.WriteLine( "- Number: {0}", message.Number );

                    pop3Client.Retrieve( message );

                    Console.WriteLine( "\t* MessageId: {0}", message.MessageId );
                    Console.WriteLine( "\t* Date: {0}", message.Date );
                    Console.WriteLine( "\t* From: {0}", message.From );
                    Console.WriteLine( "\t* To: {0}", message.To );
                    Console.WriteLine( "\t* Subject: {0}", message.Subject );
                    Console.WriteLine( "\t* Body Length: {0}", message.Body.Length );
                    Console.WriteLine( );
                }

                Console.WriteLine( "Disconnecting...{0}", Environment.NewLine );
                pop3Client.Disconnect( );
            }
            catch ( Exception ex )
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine( ex.Message );
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
    private void ListMessages()
    {
        lblMessage.Text = "";
        lblMessage.ForeColor = Color.Green;

        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = Session["Password"].ToString();

            // SSL settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = Pop3SslSecurityMode.Implicit;
            }

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to SSL enabled POP3 Mail server.<br><hr>";

            // get list of messages
            Pop3MessageInfoCollection msgCollection = client.ListMessages();
            gvMessages.DataSource = msgCollection;
            gvMessages.DataBind();

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
Пример #42
0
    /// <summary>
    /// fetch all messages from a POP3 server
    /// </summary>
    /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param>
    /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param>
    /// <param name="useSsl">Whether or not to use SSL to connect to server</param>
    /// <param name="username">Username of the user on the server</param>
    /// <param name="password">Password of the user on the server</param>
    /// <param name="deleteImagAfterFetch">If true images on Pop3 will be deleted after beeing fetched</param>
    /// <returns>All Messages on the POP3 server</returns>
    public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password, bool deleteImagAfterFetch)
    {
        // The client disconnects from the server when being disposed
        using (Pop3Client client = new Pop3Client())
        {
            // Connect to the server
            client.Connect(hostname, port, useSsl);
            client.Authenticate(username, password);
            int messageCount = client.GetMessageCount();

            // We want to download all messages
            List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
            for (int i = messageCount; i > 0; i--)
            {
                allMessages.Add(client.GetMessage(i));

                if (deleteImagAfterFetch)
                {
                    client.DeleteMessage(i);
                }
            }
            return allMessages;
        }
    }
Пример #43
0
        public void ListOk( )
        {
            Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", 995, true );

            List<Pop3Message> messages = new List<Pop3Message>( pop3Client.List( ) );
            Assert.AreEqual( 2, messages.Count );
            Assert.AreEqual( 1, messages[ 0 ].Number );
            Assert.AreEqual( 1586, messages[ 0 ].Bytes );
            Assert.IsFalse( messages[ 0 ].Retrieved );
            Assert.AreEqual( 2, messages[ 1 ].Number );
            Assert.AreEqual( 1584, messages[ 1 ].Bytes );
            Assert.IsFalse( messages[ 1 ].Retrieved );
        }
Пример #44
0
    ///////////////////////////////////////////////////////////////////////
    protected void fetch_messages(string user, string password, int projectid)
    {

        List<string> messages = null;
        Regex regex = new Regex("\r\n");
        using (Pop3Client client = new Pop3Client())
        {
            try
            {
                write_line("****connecting to server:");
                int port = 110;
                if (Pop3Port != "")
                {
                    port = Convert.ToInt32(Pop3Port);
                }

                bool use_ssl = false;
                if (Pop3UseSSL != "")
                {
                    use_ssl = Pop3UseSSL == "1" ? true : false;
                }

                write_line("Connecting to pop3 server");
                client.Connect(Pop3Server, port, use_ssl);
                write_line("Autenticating");
                client.Authenticate(user, password);


                write_line("Getting list of documents");
                messages = client.GetMessageUids();
            }
            catch (Exception e)
            {
                write_line("Exception trying to talk to pop3 server");
                write_line(e);
                return;
            }


            int message_number = 0;


            // loop through the messages
            for (int i = 0; i < messages.Count; i++)
            {
                heartbeat_datetime = DateTime.Now; // because the watchdog is watching

                if (state != service_state.STARTED)
                {
                    break;
                }

                // fetch the message

                write_line("Getting Message:" + messages[i]);
                message_number = Convert.ToInt32(messages[i]);
                Message mimeMessage = null;

                try
                {
                    mimeMessage = client.GetMessage(message_number);
                }
                catch (Exception exception)
                {
                    write_to_log("Error getting message" );
                    write_to_log(exception.ToString());
                    continue;
                }
                    

                // for diagnosing problems
                if (MessageOutputFile != "")
                {
                    File.WriteAllBytes(MessageOutputFile, mimeMessage.RawMessage);
                }

                // break the message up into lines

                string from = mimeMessage.Headers.From.Address;
                string subject = mimeMessage.Headers.Subject;




                write_line("\nFrom: " + from);

                write_line("Subject: " + subject);

                if (!string.IsNullOrEmpty(SubjectMustContain) && subject.IndexOf(SubjectMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because subject does not contain: " + SubjectMustContain);
                    continue;
                }

                bool bSkip = false;
                foreach (string subjectCannotContainString in SubjectCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(subjectCannotContainString))
                    {
                        if (subject.IndexOf(subjectCannotContainString, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because subject cannot contain: " + subjectCannotContainString);
                            bSkip = true;
                            break;  // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(FromMustContain) && from.IndexOf(FromMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because from does not contain: " + FromMustContain);
                    continue; // that is, skip to next message
                }

                foreach (string fromCannotContainStrings in FromCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(fromCannotContainStrings))
                    {
                        if (from.IndexOf(fromCannotContainStrings, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because from cannot contain: " + fromCannotContainStrings);
                            bSkip = true;
                            break; // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                write_line("calling insert_bug.aspx");
                string Url = InsertBugUrl;

                // Try to parse out the bugid from the subject line
                string bugidString = TrackingIdString;
                if (string.IsNullOrEmpty(TrackingIdString))
                {
                    bugidString = "DO NOT EDIT THIS:";
                }

                int pos = subject.IndexOf(bugidString, StringComparison.OrdinalIgnoreCase);

                if (pos >= 0)
                {
                    // position of colon
                    pos = subject.IndexOf(":", pos);
                    pos++;
                    // position of close paren
                    int pos2 = subject.IndexOf(")", pos);
                    if (pos2 > pos)
                    {
                        string bugid_string = subject.Substring(pos, pos2 - pos);
                        write_line("BUGID=" + bugid_string);
                        try
                        {
                            int bugid = Int32.Parse(bugid_string);
                            Url += "?bugid=" + Convert.ToString(bugid);
                            write_line("updating existing bug " + Convert.ToString(bugid));
                        }
                        catch (Exception e)
                        {
                            write_line("bugid not numeric " + e.Message);
                        }
                    }
                }

                string rawMessage = Encoding.Default.GetString(mimeMessage.RawMessage);
                string post_data = "username="******"&password="******"&projectid=" + Convert.ToString(projectid)
                                   + "&from=" + HttpUtility.UrlEncode(from)
                                   + "&short_desc=" + HttpUtility.UrlEncode(subject)
                                   + "&message=" + HttpUtility.UrlEncode(rawMessage);

                byte[] bytes = Encoding.UTF8.GetBytes(post_data);


                // send request to web server
                HttpWebResponse res = null;
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);


                    req.Credentials = CredentialCache.DefaultCredentials;
                    req.PreAuthenticate = true;

                    //req.Timeout = 200; // maybe?
                    //req.KeepAlive = false; // maybe?

                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.ContentLength = bytes.Length;
                    Stream request_stream = req.GetRequestStream();
                    request_stream.Write(bytes, 0, bytes.Length);
                    request_stream.Close();
                    res = (HttpWebResponse)req.GetResponse();
                }
                catch (Exception e)
                {
                    write_line("HttpWebRequest error url=" + Url);
                    write_line(e);
                }

                // examine response

                if (res != null)
                {

                    int http_status = (int)res.StatusCode;
                    write_line(Convert.ToString(http_status));

                    string http_response_header = res.Headers["BTNET"];
                    res.Close();

                    if (http_response_header != null)
                    {
                        write_line(http_response_header);

                        // only delete message from pop3 server if we
                        // know we stored in on the web server ok
                        if (MessageInputFile == ""
                            && http_status == 200
                            && DeleteMessagesOnServer == "1"
                            && http_response_header.IndexOf("OK") == 0)
                        {
                            write_line("sending POP3 command DELE");
                            client.DeleteMessage(message_number);
                        }
                    }
                    else
                    {
                        write_line("BTNET HTTP header not found.  Skipping the delete of the email from the server.");
                        write_line("Incrementing total error count");
                        total_error_count++;
                    }
                }
                else
                {
                    write_line("No response from web server.  Skipping the delete of the email from the server.");
                    write_line("Incrementing total error count");
                    total_error_count++;
                }

                if (total_error_count > TotalErrorsAllowed)
                {
                    write_line("Stopping because total error count > TotalErrorsAllowed");
                    stop();
                }


            }  // end for each message


            if (MessageInputFile == "")
            {
                write_line("\nsending POP3 command QUIT");
                client.Disconnect();
            }
            else
            {
                write_line("\nclosing input file " + MessageInputFile);
            }
        }
    }
Пример #45
0
        public void RetrieveHeaderListOk( )
        {
            Pop3Client pop3Client = new Pop3Client( new OnlyHeadersDummyNetworkOperations( ) );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" );

            List<Pop3Message> messages = new List<Pop3Message>( pop3Client.List( ) );

            pop3Client.RetrieveHeader( messages );
            Assert.IsFalse( messages[ 0 ].Retrieved );
            Assert.IsNotNull( messages[ 0 ].RawHeader );
            Assert.IsNull( messages[ 0 ].RawMessage );
            Assert.AreEqual( "Rodolfo Finochietti <*****@*****.**>", messages[ 0 ].From );
            Assert.AreEqual( "\"[email protected]\" <*****@*****.**>", messages[ 0 ].To );
            Assert.AreEqual( "Tue, 13 Nov 2012 10:57:04 -0500", messages[ 0 ].Date );
            Assert.AreEqual( "<*****@*****.**>", messages[ 0 ].MessageId );
            Assert.AreEqual( "Test 1", messages[ 0 ].Subject );
            Assert.AreEqual( "quoted-printable", messages[ 0 ].ContentTransferEncoding );
            Assert.IsNull( messages[ 0 ].Body );
            Assert.AreEqual( "1.0", messages[ 0 ].GetHeaderData( "MIME-Version" ) );
            Assert.AreEqual( "Ac3Bt4nMDtM3y3FyQ1yd71JVtsSGJQ==", messages[ 0 ].GetHeaderData( "Thread-Index" ) );
            Assert.IsFalse( messages[ 1 ].Retrieved );
            Assert.IsNotNull( messages[ 1 ].RawHeader );
            Assert.IsNull( messages[ 1 ].RawMessage );
            Assert.AreEqual( "Rodolfo Finochietti <*****@*****.**>", messages[ 1 ].From );
            Assert.AreEqual( "\"[email protected]\" <*****@*****.**>", messages[ 1 ].To );
            Assert.AreEqual( "Tue, 13 Nov 2012 10:57:28 -0500", messages[ 1 ].Date );
            Assert.AreEqual( "<*****@*****.**>", messages[ 1 ].MessageId );
            Assert.AreEqual( "Test 2", messages[ 1 ].Subject );
            Assert.AreEqual( "base64", messages[ 1 ].ContentTransferEncoding );
            Assert.IsNull( messages[ 1 ].Body );
            Assert.AreEqual( "Microsoft-MacOutlook/14.2.4.120824", messages[ 1 ].GetHeaderData( "user-agent:" ) );
            Assert.AreEqual( String.Empty, messages[ 1 ].GetHeaderData( "X-MS-Has-Attach:" ) );
        }
Пример #46
0
        public void RetrieveFoldedHeaderOk( )
        {
            Pop3Client pop3Client = new Pop3Client( new OnlyHeadersDummyNetworkOperations( ) );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" );

            List<Pop3Message> messages = new List<Pop3Message>( pop3Client.List( ) );

            pop3Client.RetrieveHeader( messages[ 0 ] );
            Assert.IsFalse( messages[ 0 ].Retrieved );
            Assert.IsNotNull( messages[ 0 ].RawHeader );
            Assert.IsNull( messages[ 0 ].RawMessage );
            Assert.AreEqual( "multipart/mixed;boundary=\"--boundary_0_........-....-....-....-............\"", messages[ 0 ].GetHeaderData( "Content-Type-Custom" ) );
        }
Пример #47
0
        public void DeleteOk( )
        {
            Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( );
            mockNetworkOperations.Setup( no => no.Read( ) ).Returns( "+OK" );

            Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", false );

            pop3Client.Delete( new Pop3Message( ) { Number = 1 } );
        }
Пример #48
0
        public void DeleteFailNullArgument( )
        {
            Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( );
            mockNetworkOperations.Setup( no => no.Read( ) ).Returns( "+OK" );

            Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", true );
            Assert.IsTrue( pop3Client.IsConnected );

            pop3Client.Delete( null );
        }
Пример #49
0
        public void SendCommandFailNullResponse( )
        {
            Mock<INetworkOperations> mockNetworkOperations = new Mock<INetworkOperations>( );
            mockNetworkOperations.SetupSequence( no => no.Read( ) )
                                                .Returns( "+OK" )
                                                .Returns( String.Empty );

            Pop3Client pop3Client = new Pop3Client( mockNetworkOperations.Object );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD", false );
        }
    protected void ButtonSearch_Click(object sender, EventArgs e)
    {
        try
        {
            Class1 class1 = new Class1();
            SqlConnection con2 = new SqlConnection(class1.conn);
            con2.Open();
            SqlCommand com1 = new SqlCommand("select email from screenshots where empid='" + Convert.ToString(TextBox3.Text) + "'", con2);
            SqlDataReader sdr1;
            sdr1 = com1.ExecuteReader();
            sdr1.Read();

            if (sdr1.FieldCount > 0)
            {
                var client = new Pop3Client();
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate(email1, Convert.ToString(TextBox4.Text));

                var count = client.GetMessageCount();

                for (int i = count; i >= (count - 10); i--)
                {
                    Message message = client.GetMessage(i);
                    String from = Convert.ToString(message.Headers.From.Address);
                    if (from.Equals(sdr1[0]))
                    {
                        String pathString = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Convert.ToString(TextBox3.Text));

                        List<MessagePart> attachments = message.FindAllAttachments();
                        foreach (MessagePart attachment in attachments)
                        {
                            String filename = attachment.FileName;

                            byte[] Content = attachment.Body;
                            MemoryStream ms = new MemoryStream(Content);
                            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                            String path1 = pathString + "\\" + filename;
                            img.Save(path1);
                            SqlConnection con4 = new SqlConnection(class1.conn);
                            con4.Open();
                            try
                            {
                                SqlCommand com = new SqlCommand("insert into images values ('" + Convert.ToString(TextBox3.Text) +"/"+ filename + "', '" + Convert.ToString(TextBox3.Text) + "')", con4);
                                int i1 = com.ExecuteNonQuery();
                            }
                            catch(Exception)
                            {
                                func3();
                            }
                            con4.Close();
                        }
                    }
                }
                con2.Close();
                func3();
            }

        }
        catch(Exception)
        {
            func3();
            Label3.Visible = true;
            Label3.Text = "";
        }
    }
Пример #51
0
    ///////////////////////////////////////////////////////////////////////
    protected async void fetch_messages(string user, string password, int projectid)
    {

        List<string> messages = null;
        Regex regex = new Regex("\r\n");
        using (Pop3Client client = new Pop3Client())
        {
            try
            {
                write_line("****connecting to server:");
                int port = 110;
                if (Pop3Port != "")
                {
                    port = Convert.ToInt32(Pop3Port);
                }

                bool use_ssl = false;
                if (Pop3UseSSL != "")
                {
                    use_ssl = Pop3UseSSL == "1" ? true : false;
                }

                write_line("Connecting to pop3 server");
                client.Connect(Pop3Server, port, use_ssl);
                write_line("Autenticating");
                client.Authenticate(user, password);


                write_line("Getting list of documents");
                messages = client.GetMessageUids();
            }
            catch (Exception e)
            {
                write_line("Exception trying to talk to pop3 server");
                write_line(e);
                return;
            }


            int message_number = 0;


            // loop through the messages
            for (int i = 0; i < messages.Count; i++)
            {
                heartbeat_datetime = DateTime.Now; // because the watchdog is watching

                if (state != service_state.STARTED)
                {
                    break;
                }

                // fetch the message

                write_line("Getting Message:" + messages[i]);
                message_number = Convert.ToInt32(messages[i]);
                Message mimeMessage = null;

                try
                {
                    mimeMessage = client.GetMessage(message_number);
                }
                catch (Exception exception)
                {
                    write_to_log("Error getting message");
                    write_to_log(exception.ToString());
                    continue;
                }


                // for diagnosing problems
                if (MessageOutputFile != "")
                {
                    File.WriteAllBytes(MessageOutputFile, mimeMessage.RawMessage);
                }

                // break the message up into lines

                string from = mimeMessage.Headers.From.Address;
                string subject = mimeMessage.Headers.Subject;




                write_line("\nFrom: " + from);

                write_line("Subject: " + subject);

                if (!string.IsNullOrEmpty(SubjectMustContain) && subject.IndexOf(SubjectMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because subject does not contain: " + SubjectMustContain);
                    continue;
                }

                bool bSkip = false;
                foreach (string subjectCannotContainString in SubjectCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(subjectCannotContainString))
                    {
                        if (subject.IndexOf(subjectCannotContainString, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because subject cannot contain: " + subjectCannotContainString);
                            bSkip = true;
                            break;  // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(FromMustContain) && from.IndexOf(FromMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because from does not contain: " + FromMustContain);
                    continue; // that is, skip to next message
                }

                foreach (string fromCannotContainStrings in FromCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(fromCannotContainStrings))
                    {
                        if (from.IndexOf(fromCannotContainStrings, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because from cannot contain: " + fromCannotContainStrings);
                            bSkip = true;
                            break; // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                write_line("calling insert_bug.aspx");

                bool useBugId = false;

                // Try to parse out the bugid from the subject line
                string bugidString = TrackingIdString;
                if (string.IsNullOrEmpty(TrackingIdString))
                {
                    bugidString = "DO NOT EDIT THIS:";
                }

                int pos = subject.IndexOf(bugidString, StringComparison.OrdinalIgnoreCase);

                if (pos >= 0)
                {
                    // position of colon
                    pos = subject.IndexOf(":", pos);
                    pos++;
                    // position of close paren
                    int pos2 = subject.IndexOf(")", pos);
                    if (pos2 > pos)
                    {
                        string bugid_string = subject.Substring(pos, pos2 - pos);
                        write_line("BUGID=" + bugid_string);
                        try
                        {
                            int bugid = Int32.Parse(bugid_string);
                            useBugId = true;
                            write_line("updating existing bug " + Convert.ToString(bugid));
                        }
                        catch (Exception e)
                        {
                            write_line("bugid not numeric " + e.Message);
                        }
                    }
                }

                
                // send request to web server
                try
                {
                    HttpClientHandler handler = new HttpClientHandler
                    {
                        AllowAutoRedirect = true,
                        UseCookies = true,
                        CookieContainer = new CookieContainer()
                    };
                    using (var httpClient = new HttpClient(handler))
                    {
                        var loginParameters = new Dictionary<string, string>
                        {
                           { "user", ServiceUsername },
                           { "password", ServicePassword }
                        };

                        HttpContent loginContent = new FormUrlEncodedContent(loginParameters);
                        var loginResponse = await httpClient.PostAsync(LoginUrl, loginContent);
                        loginResponse.EnsureSuccessStatusCode();

                        string rawMessage = Encoding.Default.GetString(mimeMessage.RawMessage);
                        var postBugParameters = new Dictionary<string, string>
                        {
                           { "projectId", Convert.ToString(projectid) },
                           { "fromAddress", from },
                           { "shortDescription", subject},
                           { "message", rawMessage}
                           //Any other paramters go here
                        };
                        if (useBugId)
                        {
                            postBugParameters.Add("bugId", bugidString);
                        }

                        HttpContent bugContent = new FormUrlEncodedContent(postBugParameters);
                        var postBugResponse = await httpClient.PostAsync(InsertBugUrl, bugContent);

                        postBugResponse.EnsureSuccessStatusCode();
                    }
                    if (MessageInputFile == "" && DeleteMessagesOnServer == "1")
                    {
                        write_line("sending POP3 command DELE");
                        client.DeleteMessage(message_number);
                    }
                }
                catch (Exception e)
                {
                    write_line("HttpWebRequest error url=" + InsertBugUrl);
                    write_line(e);
                    write_line("Incrementing total error count");
                    total_error_count++;
                }

                // examine response
                if (total_error_count > TotalErrorsAllowed)
                {
                    write_line("Stopping because total error count > TotalErrorsAllowed");
                    stop();
                }


            }  // end for each message


            if (MessageInputFile == "")
            {
                write_line("\nsending POP3 command QUIT");
                client.Disconnect();
            }
            else
            {
                write_line("\nclosing input file " + MessageInputFile);
            }
        }
    }
Пример #52
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user_yetki_id"] != (object)1)
        {
            Response.Redirect("../Default2.aspx");
        }

        int emailId = -1;
        if (Request.QueryString["emailId"] == null)
        {
            Response.Redirect("Mesaj-List-Gmail.aspx");
            Response.Flush();
            Response.End();
        }
        else
            Email = Session["email"].ToString();
        Password = Session["pwd"].ToString();
        emailId = Convert.ToInt32(Request.QueryString["emailId"]);
        Email email = null;
        List<MessagePart> msgParts = null;
        using (Pop3Client client = new Pop3Client(Host, Port, Email, Password, true))
        {
            client.Connect();
            email = client.FetchEmail(emailId);
            msgParts = client.FetchMessageParts(emailId);
        }
        if (email == null || msgParts == null)
        {
            Response.Redirect("Mesaj-List-Gmail.aspx");
            Response.Flush();
            Response.End();
        }
        MessagePart preferredMsgPart = FindMessagePart(msgParts, "text/html");
        if (preferredMsgPart == null)
            preferredMsgPart = FindMessagePart(msgParts, "text/plain");
        else if (preferredMsgPart == null && msgParts.Count > 0)
            preferredMsgPart = msgParts[0];
        string contentType, charset, contentTransferEncoding, body = null;
        if (preferredMsgPart != null)
        {
            contentType = preferredMsgPart.Headers["Content-Type"];
            charset = "us-ascii";
            contentTransferEncoding = preferredMsgPart.Headers["Content-Transfer-Encoding"];
            Match m = CharsetRegex.Match(contentType);
            if (m.Success)
                charset = m.Groups["charset"].Value;
            HeadersLiteral.Text = contentType != null ? "Content-Type: " + contentType + "<br />" : string.Empty;
            HeadersLiteral.Text += contentTransferEncoding != null ? "Content-Transfer-Encoding: " + contentTransferEncoding : string.Empty;
            if (contentTransferEncoding != null)
            {
                if (contentTransferEncoding.ToLower() == "base64")
                    body = DecodeBase64String(charset, preferredMsgPart.MessageText);
                else if (contentTransferEncoding.ToLower() == "quoted-printable")
                    body = DecodeQuotedPrintableString(preferredMsgPart.MessageText);
                else
                    body = preferredMsgPart.MessageText;
            }
            else
                body = preferredMsgPart.MessageText;
        }
        EmailIdLiteral.Text = Convert.ToString(emailId);
        DateLiteral.Text = email.UtcDateTime.ToString(); ;
        FromLiteral.Text = email.From;
        SubjectLiteral.Text = email.Subject;
        BodyLiteral.Text = preferredMsgPart != null ? (preferredMsgPart.Headers["Content-Type"].IndexOf("text/plain") != -1 ? "<pre>" + FormatUrls(body) + "</pre>" : body) : null;
        ListAttachments(msgParts);
    }
Пример #53
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user_yetki_id"] != (object)1)
        {
            Response.Redirect("../Default2.aspx");
        }

        int page = 1;
        if (Request.QueryString["page"] == null)
        {
            Response.Redirect("Mesaj-List-Gmail.aspx?page=1");
            Response.Flush();
            Response.End();
        }
        else
            page = Convert.ToInt32(Request.QueryString["page"]);
        try
        {
            Email = Session["email"].ToString();
            Password = Session["pwd"].ToString();
        }
        catch (Exception ex) { Response.Redirect("Mesaj-Listesi.aspx"); }
        int totalEmails;
        List<Email> emails;
        string emailAddress;
        using (Pop3Client client = new Pop3Client(Host, Port, Email, Password, true))
        {
            emailAddress = client.Email;
            client.Connect();
            totalEmails = client.GetEmailCount();
            emails = client.FetchEmailList(((page - 1) * NoOfEmailsPerPage) + 1, NoOfEmailsPerPage);
        }
        int totalPages;
        int mod = totalEmails % NoOfEmailsPerPage;
        if (mod == 0)
            totalPages = totalEmails / NoOfEmailsPerPage;
        else
            totalPages = ((totalEmails - mod) / NoOfEmailsPerPage) + 1;
        for (int i = 0; i < emails.Count; i++)
        {
            Email email = emails[i];
            int emailId = ((page - 1) * NoOfEmailsPerPage) + i + 1;
            TableCell noCell = new TableCell();
            noCell.CssClass = "emails-table-cell";
            noCell.Text = Convert.ToString(emailId);
            TableCell fromCell = new TableCell();
            fromCell.CssClass = "emails-table-cell";
            fromCell.Text = email.From;
            TableCell subjectCell = new TableCell();
            subjectCell.CssClass = "emails-table-cell";
            subjectCell.Style["width"] = "300px";
            subjectCell.Text = String.Format(DisplayEmailLink, emailId, email.Subject);
            TableCell dateCell = new TableCell();
            dateCell.CssClass = "emails-table-cell";
            if (email.UtcDateTime != DateTime.MinValue)
                dateCell.Text = email.UtcDateTime.ToString();
            TableRow emailRow = new TableRow();
            emailRow.Cells.Add(noCell);
            emailRow.Cells.Add(fromCell);
            emailRow.Cells.Add(subjectCell);
            emailRow.Cells.Add(dateCell);
            EmailsTable.Rows.AddAt(2 + i, emailRow);
        }
        if (totalPages > 1)
        {
            if (page > 1)
                PreviousPageLiteral.Text = String.Format(SelfLink, page - 1, "Previous Page");
            if (page > 0 && page < totalPages)
                NextPageLiteral.Text = String.Format(SelfLink, page + 1, "Next Page");
        }
        EmailFromLiteral.Text = Convert.ToString(((page - 1) * NoOfEmailsPerPage) + 1);
        EmailToLiteral.Text = Convert.ToString(page * NoOfEmailsPerPage);
        EmailTotalLiteral.Text = Convert.ToString(totalEmails);
        EmailLiteral.Text = emailAddress;
    }