コード例 #1
1
 public void Fetch(Action<Message> process)
 {
     var seenUids = File.Exists(seenUidsFile) ? new HashSet<string>(File.ReadAllLines(seenUidsFile)) : new HashSet<string>();
     using (var client = new Pop3Client())
     {
         pop3Authorize(client);
         List<string> messageUids = client.GetMessageUids();
         foreach (var msgInfo in messageUids.Select((uid, index) => new{uid, index}).Where(msgInfo => !seenUids.Contains(msgInfo.uid)))
         {
             try
             {
                 Message message = client.GetMessage(msgInfo.index+1);
                 message.Save(new FileInfo(msgInfo.uid + ".mime"));
                 process(message);
                 seenUids.Add(msgInfo.uid);
             }
             catch(Exception e)
             {
                 log.Error("Error while processing message " + msgInfo + "\r\n" + e);
             }
         }
         File.WriteAllLines(seenUidsFile, seenUids);
         for(int i=messageUids.Count; i>=1; i--) client.DeleteMessage(i);
     }
 }
コード例 #2
1
        public void Test()
        {
            const string hostName = "pop.gmail.com";
            int port = 995;
            bool useSsl = true;
            string userName = "******";
            string password = "******";

            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<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));
                }

                allMessages.ForEach(m=>Console.WriteLine("Display name: {0}", m.Headers.From.DisplayName));
            }
        }
コード例 #3
1
ファイル: Examples.cs プロジェクト: JoshKeegan/hpop
		/// <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<Message> 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<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;
			}
		}
コード例 #4
0
ファイル: Communication_Email.cs プロジェクト: weavver/data
        //-------------------------------------------------------------------------------------------
        private void ImportEmails(Communication_EmailAccounts account)
        {
            Console.WriteLine("Importing e-mails for " + account.Id + " -- " + account.Host);
               using (Pop3Client client = new Pop3Client())
               {
                    // connect
                    client.Connect(account.Host, account.Port, (account.Type == "pops"));
                    client.Authenticate(account.Username, account.Password);

                    // iterate over the messages
                    int messageCount = client.GetMessageCount();
                    List<Message> allMessages = new List<Message>(messageCount);
                    for (int i = 1; i <= messageCount; i++)
                    {
                         using (WeavverEntityContainer data = new WeavverEntityContainer())
                         {
                              //data.SearchAllTables("asdf");
                              // save to database
                              Message m = (Message) client.GetMessage(i);
                              if (m.MessagePart.IsText)
                              {
                                   Communication_Emails item = new Communication_Emails();
                                   item.From = m.Headers.From.Raw;
                                   item.Subject = m.Headers.Subject;
                                   item.Raw = System.Text.ASCIIEncoding.ASCII.GetString(m.RawMessage);
                                   data.SaveChanges();

                                   client.DeleteMessage(i);
                              }
                         }
                    }
               }
        }
コード例 #5
0
 public void TestMethodInitialize()
 {
     settings = new TestSettings();
     client = new Pop3Client();
     client.Connect(settings.Pop3Server, settings.Pop3Port, settings.Pop3UseSSL);
     client.Authenticate(settings.Pop3UserName, settings.Pop3Password);
 }
コード例 #6
0
        private static void fetchAllMessages(object sender, DoWorkEventArgs e)
        {
            int percentComplete;

            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                //client.Connect("pop.gmail.com", 995, true);
                client.Connect("mail1.stofanet.dk", 110, false);

                // Authenticate ourselves towards the server
                client.Authenticate("2241859m002", "big1234");

                // 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));
                    percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100);
                    (sender as BackgroundWorker).ReportProgress(percentComplete);
                }

                // Now return the fetched messages
                e.Result = allMessages;
            }
        }
コード例 #7
0
        public override bool HasMessages()
        {
            if (!pop3Client.Connected)
            {
                pop3Client.Dispose();
                pop3Client = new Pop3Client();
                pop3Client.Connect(HostName, Port, useSSL);
                pop3Client.Authenticate(Login, Password);
            }

            if (0 >= index)
            {
                index = count = pop3Client.GetMessageCount();
                if (0 == index)
                {
                    pop3Client.Disconnect();
                    pop3Client.Dispose();
                    pop3Client = new Pop3Client();
                    pop3Client.Connect(HostName, Port, useSSL);
                    pop3Client.Authenticate(Login, Password);
                }
                //for (int i = count; i >= 1; i -= 1)
            }
            return 0 < index;
        }
コード例 #8
0
		public void TestAutoAuthenticationUsernameAndPassword()
		{
			const string welcomeMessage = "+OK POP3 server ready";
			const string okUsername = "******";
			const string loginMessage = "+OK mrose's maildrop has 2 messages (320 octets)";
			const string serverResponses = welcomeMessage + "\r\n" + okUsername  + "\r\n" + loginMessage + "\r\n";
			Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));

			MemoryStream outputStream = new MemoryStream();

			Pop3Client client = new Pop3Client();
			client.Connect(new CombinedStream(inputStream, outputStream));

			// The Pop3Client should now have seen, that the server does not support APOP
			Assert.IsFalse(client.ApopSupported);

			client.Authenticate("mrose", "tanstaaf");

			string[] commandsFired = GetCommands(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			const string firstCommand = "USER mrose";
			Assert.AreEqual(firstCommand, commandsFired[0]);

			const string secondCommand = "PASS tanstaaf";
			Assert.AreEqual(secondCommand, commandsFired[1]);
		}
コード例 #9
0
        private void ConnectToPop3()
        {
            client = new Pop3Client();

            client.Connect(settings.Pop3Server, settings.Pop3Port, settings.Pop3UseSSL);
            client.Authenticate(settings.Pop3UserName, settings.Pop3Password);
        }
コード例 #10
0
ファイル: LogedIn.cs プロジェクト: kayabirch/H5Email
        //Connect to gmail, get emails and ad it to a MessageList
        public static List<OpenPop.Mime.Message> GetAllMessages(string hostname, int port, bool ssl, string username, string password)
        {
            try
            {
                Pop3Client client = new Pop3Client();

                    if (client.Connected)
                    {
                        client.Disconnect();
                    }

                    client.Connect(hostname, port, ssl);
                    client.Authenticate(username, password);

                    int messageCount = client.GetMessageCount();

                    List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);

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

                    return allMessages;
                }

            catch(Exception ex)
            {
                MessageBox.Show("You have written username or password wrong or something else has happened! Program will not keep going, please open it again, thank you : " + ex.Message);
                Thread.CurrentThread.Abort();
                //EmailClient.
            }

            return null;
        }
コード例 #11
0
ファイル: EmailManager.cs プロジェクト: macki/razem
        public void FetchAllMessages()
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(_hostName, _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<Message> allMessages = new List<Message>(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));
                }
            }
        }
コード例 #12
0
        /* Function to retrive Email from the POP3 Server */
        public void GetAllMails(object sender, DoWorkEventArgs e)
        {
            int percentComplete;

            using(Pop3Client client = new Pop3Client())
            {
                /* Set the Server, Port, ssl and username/password */
                client.Connect(Setting.Default.pop3_server, Setting.Default.pop3_port, Setting.Default.smtp_ssl);
                client.Authenticate(Setting.Default.username, Setting.Default.password);

                int messageCount = client.GetMessageCount();

                Debug.WriteLine(messageCount);

                /* Create a list to contain the messages */
                List<Message> allMessages = new List<Message>();

                /* A loop to calculate the progress of retriving the Emails  */
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                    percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100);
                    (sender as BackgroundWorker).ReportProgress(percentComplete);
                }
                e.Result =  allMessages;
            }
        }
コード例 #13
0
        private void ReadAllEmails()
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(EmailConfiguration.Pop3, EmailConfiguration.PopPort, true, 1800, 1800, removeCertificateCallback);

                // Authenticate ourselves towards the server
                client.Authenticate(EmailConfiguration.Email, EmailConfiguration.EmailPwd);

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

                _systemLogger.Tell(string.Format("Total messages found: {0}", messageCount));

                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    var msg = client.GetMessage(i);

                    // Now return the fetched messages
                    _emailProcessorActor.Tell(new EmailMessage(){Subject = msg.Headers.Subject, Date = msg.Headers.Date});
                }
            }
        }
コード例 #14
0
ファイル: MailClass.cs プロジェクト: rj128x/AutoOper2016
 public void processMail()
 {
     Logger.info("Проверка почты: ");
     try {
         Pop3Client client = new Pop3Client();
         client.Connect(Settings.Single.smtpServer, 110, false);
         client.Authenticate(Settings.Single.smtpUser, Settings.Single.smtpPassword);
         List<string> msgs = client.GetMessageUids();
         Logger.info(String.Format("Получено {0} сообщений ", msgs.Count));
         for (int i = 0; i < msgs.Count; i++) {
             try {
                 Logger.info("Чтение письма " + i.ToString());
                 Message msg = client.GetMessage(i);
                 List<MessagePart> files = msg.FindAllAttachments();
                 Logger.info(String.Format("Прикреплено {0} файлов", files.Count));
                 if (files.Count == 1) {
                     Logger.info(String.Format("Обработка файла {0}", files[0].FileName));
                     MessagePart file = files[0];
                     string pbrData = file.GetBodyAsText();
                     PBR.getFromText(pbrData);
                 }
             }
             catch (Exception e) {
                 Logger.error("Ошибка при обработке письма " + i);
             }
         }
     }
     catch (Exception e) {
         Logger.error("Ошибка при работе с почтой " + e.ToString());
     }
 }
コード例 #15
0
ファイル: FormInbox.cs プロジェクト: blaabjerg88/Emailclient
 public FormInbox()
 {
     InitializeComponent();
     backgroundWorker1.RunWorkerAsync();
     listMails();
     pop3client = new Pop3Client();
     messages = new Dictionary<int,Message>();
 }
コード例 #16
0
ファイル: Form1.cs プロジェクト: andresusanto/VotingCounter
        public Form1(String pas_)
        {
            InitializeComponent();
            pop3Client = new Pop3Client();
            System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;

            passEMAIL = pas_;
        }
コード例 #17
0
 public CallDataProviderImplPop3(ISelectorConfig config)
     : base(config)
 {
     this.pop3Client = new Pop3Client();
     pop3Client.Connect(HostName, Port, useSSL);
     pop3Client.Authenticate(Login, Password);
     NULL_MESSAGE = new CallMessageImpl(pop3Client, 0, this);
     
 }
コード例 #18
0
 public void Shutdown()
 {
     if (client != null && client.Connected )
     {
         client.Disconnect();
         client.Dispose();
     }
     client = null;
 }
コード例 #19
0
ファイル: OpenPop3Messaging.cs プロジェクト: James84/MailFire
        public IEnumerable<MessageDTO> GetMessages(string hostname, int port, bool useSsl, string username,
                                                   string password, int? maxNumber = null)
        {
            var allMessages = new List<MessageDTO>();

            try
            {
                // The client disconnects from the server when being disposed
                using (var client = new Pop3Client())
                {
                    client.Connect(hostname, port, useSsl);

                    client.Authenticate(username, password, AuthenticationMethod.UsernameAndPassword);

                    var maxCount = client.GetMessageCount();

                    //work out subset to take from messages
                    var messageCount = (maxNumber.HasValue && maxNumber < maxCount) ? (maxCount - maxNumber.Value) : 0;

                    //message list is 1 based
                    //loop written backwards so messages are in correct order
                    for (var i = maxCount; i > messageCount; i--)
                    {
                        var currentMessage = client.GetMessage(i);
                        var html = currentMessage.FindFirstHtmlVersion();

                        allMessages.Add(new MessageDTO
                            {
                                Body =
                                    html != null && html.Body != null
                                        ? Encoding.UTF8.GetString(html.Body)
                                        : string.Empty,
                                DateSent = currentMessage.Headers.DateSent,
                                DisplayName = currentMessage.Headers.From.DisplayName,
                                From = currentMessage.Headers.From.Address,
                                Id = currentMessage.Headers.MessageId,
                                Subject = currentMessage.Headers.Subject,
                                Uid = currentMessage.Headers.MessageId
                            });

                    }

                }
            }
            catch (Exception ex)
            {
                var path = Path.GetTempPath();
                var stream = File.OpenWrite(Path.Combine(path, "mailFireErrorLog.log"));

                using (var fileWriter = new StreamWriter(stream))
                {
                    fileWriter.Write(string.Format("Exception occurred: {0} - at {1}", ex.Message, DateTime.Now));
                }
            }
            return allMessages;
        }
コード例 #20
0
ファイル: MainForm.cs プロジェクト: ComputerKim/MailClient
        public MainForm()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.mail;

            pop3Client = new Pop3Client();

            lvwColumnSorter = new Comparer.ListViewColumnSorter();
            this.mailView.ListViewItemSorter = lvwColumnSorter;
        }
コード例 #21
0
ファイル: Form1.cs プロジェクト: camprince13/EmailClient
        static void ETest()
        {
            var client = new OpenPop.Pop3.Pop3Client(); //new POPClient();

            client.Connect("pop.gmail.com", 995, true);
            client.Authenticate("user", "pass");
            var count = client.GetMessageCount();

            OpenPop.Mime.Message message = client.GetMessage(count);
            Console.WriteLine(message.Headers.Subject);
        } //end etest
コード例 #22
0
ファイル: AdminPop.cs プロジェクト: ivanebel/ClienteCorreo
 public void ConectarPop(ServerDTO server, CuentaDTO cuenta)
 {
     cliente = new Pop3Client();
     try {
         cliente.Connect(server.PopServer, server.PopPort, server.Ssl);
         cliente.Authenticate(cuenta.User, cuenta.Password);
     }
     catch (OpenPop.Pop3.Exceptions.PopClientException ex) {
         Console.WriteLine(ex.Message);
     }
 }
コード例 #23
0
ファイル: Program.cs プロジェクト: saxx/IssueTracker
        private static void DownloadMailsAndPushToIssueTracker()
        {
            var host = Settings.Get("Pop3Host", "");
            var port = Settings.Get("Pop3Port", 110);
            var useSsl = Settings.Get("Pop3UseSsl", false);
            var username = Settings.Get("Pop3Username", "");
            var password = Settings.Get("Pop3Password", "");

            if (host.IsNoE())
            {
                Console.WriteLine("\tNo Pop3Host specified.");
                LogOwnError(new ApplicationException("No Pop3Host specified."));
                return;
            }

            try
            {
                Console.WriteLine("\tConnecting to POP3 server {0}:{1} ({4}) using {2} / {3} ...", host, port, username, password, useSsl ? "SSL" : "no SSL");

                using (var pop3Client = new Pop3Client())
                {
                    pop3Client.Connect(host, port, useSsl);
                    if (username.HasValue())
                        pop3Client.Authenticate(username, password);

                    Console.WriteLine("\tFetching message count ...");
                    var messageCount = pop3Client.GetMessageCount();

                    for (var i = 1; i <= messageCount; i++)
                    {
                        try
                        {
                            Console.WriteLine("\tFetching message {0} / {1} ...", i, messageCount);
                            var message = pop3Client.GetMessage(i);

                            if (PushToIssueTracker(message))
                                pop3Client.DeleteMessage(i);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("\tUnable to fetch or push message: " + ex);
                            LogOwnError(new ApplicationException("Unable to fetch or push message: " + ex.Message, ex));
                        }
                    }

                    pop3Client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\tUnable to download mails: " + ex);
                LogOwnError(new ApplicationException("Unable to download mails: " + ex.Message, ex));
            }
        }
コード例 #24
0
ファイル: Login.cs プロジェクト: henkall/mail-client1
        public Login()
        {
            InitializeComponent();
            pop3Client = new Pop3Client();

            /// Makes the onclick work
            view_mails.AfterSelect += new TreeViewEventHandler(ListMessagesMessageSelected);
            atached_file.AfterSelect += new TreeViewEventHandler(ListAttachmentsAttachmentSelected);

            /// Makes the Rijndael Key
            myKey = Rijndael.Create();
        }
コード例 #25
0
ファイル: EmailHandler.cs プロジェクト: cberberian/Brain
 private static GetEmailResponse GetPopEmail()
 {
     var client = new Pop3Client();
     client.Connect("pop.gmail.com", 995, true);
     client.Authenticate("*****@*****.**", "Woq0wy951", AuthenticationMethod.UsernameAndPassword);
     var count = client.GetMessageCount();
     var message = client.GetMessage(count);
     Console.WriteLine(message.Headers.Subject);
     return new GetEmailResponse
     {
     };
 }
コード例 #26
0
        //TODO: change the return type as needed
        public static List<SourcedAdoNetLog> PopGetLogEmails(int numEmails = 50, string email = "*****@*****.**", string pass = "******")
        {
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect("pop.gmail.com", 995, true);

                // Authenticate ourselves towards the server
                client.Authenticate(email, pass, AuthenticationMethod.UsernameAndPassword);

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

                // We want to download all messages
                List<SourcedAdoNetLog> allLogs = new List<SourcedAdoNetLog>();

                // 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--)
                { //TODO: i > messageCount - numEmails;     ** make sure that is greater than 0 though..
                    var message = client.GetMessage(i);
                    if (message == null) continue;

                    var plainText = message.FindFirstPlainTextVersion();
                    if (plainText == null) continue;

                    var body = plainText.GetBodyAsText();
                    try
                    {
                        var json = body.FromJson<AdoNetLog>();
                        SourcedAdoNetLog srcLog = new SourcedAdoNetLog
                        {
                            Source = "Email:\n" + email,
                            Date = json.Date,
                            Level = json.Level,
                            Logger = json.Logger,
                            Message = json.Message,
                            Exception = json.Exception,
                        };
                        allLogs.Add(srcLog);
                    }
                    catch (Exception e)
                    {
                        Log.Error(String.Format("Failed to parse an AdoNetLog out from the following email body:\n{0}", body), e);
                    }

                }
                return allLogs;
            }
        }
コード例 #27
0
        public void TestAccountLoginDelayResponseApop()
        {
            const string welcomeMessage = "+OK POP3 server ready <*****@*****.**>";
            const string loginMessage = "-ERR [LOGIN-DELAY] wait some time before loggin in";
            const string serverResponses = welcomeMessage + "\r\n" + loginMessage + "\r\n";
            Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));

            MemoryStream outputStream = new MemoryStream();

            Pop3Client client = new Pop3Client();
            client.Connect(new CombinedStream(inputStream, outputStream));

            Assert.Throws<LoginDelayException>(delegate { client.Authenticate("foo", "bar", AuthenticationMethod.Apop); });
        }
コード例 #28
0
        /// <summary>
        /// Example showing:
        ///  - how to set timeouts
        ///  - how to override the SSL certificate checks with your own implementation
        /// </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="timeouts">Read and write timeouts used by the Pop3Client</param>
        public static void BypassSslCertificateCheck(string hostname, int port, int timeouts)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server using SSL with specified settings
                // true here denotes that we connect using SSL
                // The certificateValidator can validate the SSL certificate of the server.
                // This might be needed if the server is using a custom normally untrusted certificate
                client.Connect(hostname, port, true, timeouts, timeouts, certificateValidator);

                // Do something extra now that we are connected to the server
            }
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: petermunnings/funwithoiky
        private static List<Message> GetNewMessages(Pop3Client pop3Client)
        {
            var allMessages = new List<Message>();

            pop3Client.Connect(Hostname, Port, UseSsl);
            pop3Client.Authenticate(Username, Password);
            var messageCount = pop3Client.GetMessageCount();

            for (var i = messageCount; i > 0; i--)
            {
                allMessages.Add(pop3Client.GetMessage(i));
            }
            return allMessages;
        }
コード例 #30
0
ファイル: Inbox.cs プロジェクト: bjeffe/Inbox
        public Inbox()
        {
            InitializeComponent();

            DefaultLogger.SetLog(new FileLogger());

            // Enable file logging and include verbose information
            FileLogger.Enabled = true;
            FileLogger.Verbose = true;

            pop3Client = new Pop3Client();

            treeViewmails.AfterSelect += new TreeViewEventHandler(ListMessagesMessageSelected);
            treeViewFiles.AfterSelect +=new TreeViewEventHandler(ListAttachmentsAttachmentSelected);
        }
コード例 #31
0
ファイル: Postman.cs プロジェクト: RikkiRu/oopWork14
        public Postman()
        {
            hostUsername = "******";
            hostAddress = hostUsername + "@gmail.com";
            hostPassword = "******";

            client = new Pop3Client();
            Connect();

            if (client.Connected) {
                timer = new Timer(600000.0);
                timer.Elapsed += new ElapsedEventHandler(CheckMailBox);
                timer.Start();
            }
        }
コード例 #32
0
        private void EnviarRespostaAtuomatica_Tick(object sender, ElapsedEventArgs e)
        {
            /*
             *    LENDO OS E-MAILS QUE CHEGAM NA CAIXA DE ENTRADA
             */
            try
            {
                using (var mail = new OpenPop.Pop3.Pop3Client())
                {
                    /*
                     *  Classe que conecta e autentica com o e-mail [email protected]
                     */
                    mail.Connect(hostname, port, useTls);
                    mail.Authenticate(username, password);
                    int contadorMensagem = mail.GetMessageCount();
                    listaEmails.Clear();

                    for (int i = contadorMensagem; i > 0; i--)
                    {
                        /*
                         *  Percorre os e-mails da caixa de entrada e pega algumas informações:
                         *  - ID do e-mail
                         *  - Assunto (para verificar se deve ou não responder)
                         *  - Remetente
                         *  - Data de recebimento da mensagem
                         *  Ao final, aramzena as informações de cada mensagem numa Lista, na memória.
                         */
                        var popEmail = mail.GetMessage(i);

                        string mailText = string.Empty;
                        var    popText  = popEmail.FindFirstPlainTextVersion();
                        if (popText != null)
                        {
                            mailText = popText.GetBodyAsText();
                        }

                        listaEmails.Add(new Email()
                        {
                            Id            = popEmail.Headers.MessageId,
                            Assunto       = popEmail.Headers.Subject,
                            De            = popEmail.Headers.From.Address,
                            Para          = string.Join("; ", popEmail.Headers.To.Select(to => to.Address)),
                            Data          = popEmail.Headers.Date,
                            ConteudoTexto = mailText
                        }
                                        );
                    }

                    if (mail.GetMessageCount() > 0)
                    {
                        /*
                         * Enquanto tiver e-mails na caixa de entrada, o programa faz o seguinte:
                         * - Pega o ID de cada mensagem e faz uma varredura no arquivo "emails_respondidos.txt", localizado no servidor
                         * - Se o ID NÃO CONSTAR no arquivo, o programa ENVIA uma resposta automática, de acordo com o assunto recebido.
                         * - Adiciona o e-mail enviado à lista de e-mails respondidos.
                         * - Se o ID CONSTAR, ignora a mensagem e NÃO ENVIA a resposta.
                         */
                        using (SmtpClient objSmtp = new SmtpClient(hostname, 587))
                        {
                            objSmtp.EnableSsl   = true;
                            objSmtp.Credentials = new NetworkCredential(username, password);

                            idsLidos = File.ReadLines(caminhoArquivo).ToList();

                            foreach (Email item in listaEmails)
                            {
                                if (!idsLidos.Contains(item.Id))
                                {
                                    if (item.Assunto == "Contato do Site - \"Matrícula mais de um segmento\"")
                                    {
                                        Escrever(item.Id, item.Data);
                                        objSmtp.Send(Mensagens.GerarMensagemDefault(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto)));
                                        Console.WriteLine("Respostas enviadas...");
                                    }
                                    else if (item.Assunto == "Contato do Site - \"Matrícula Berçário\"")
                                    {
                                        Escrever(item.Id, item.Data);
                                        objSmtp.Send(Mensagens.GerarMensagemBercario(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto)));
                                        Console.WriteLine("Respostas enviadas...");
                                    }
                                    else if (item.Assunto == "Contato do Site - \"Matrícula Infantil\"")
                                    {
                                        Escrever(item.Id, item.Data);
                                        objSmtp.Send(Mensagens.GerarMensagemInfantil(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto)));
                                        Console.WriteLine("Respostas enviadas...");
                                    }
                                    else if (item.Assunto == "Contato do Site - \"Matrícula Fundamental 1\"")
                                    {
                                        Escrever(item.Id, item.Data);
                                        objSmtp.Send(Mensagens.GerarMensagemFundamental_1(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto)));
                                        Console.WriteLine("Respostas enviadas...");
                                    }
                                    else if (item.Assunto == "Contato do Site - \"Matrícula Fundamental 2\"")
                                    {
                                        Escrever(item.Id, item.Data);
                                        objSmtp.Send(Mensagens.GerarMensagemFundamental_2(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto)));
                                        Console.WriteLine("Respostas enviadas...");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }