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);
     }
 }
Esempio n. 2
0
        //-------------------------------------------------------------------------------------------
        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);
                              }
                         }
                    }
               }
        }
Esempio n. 3
0
        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));
            }
        }
Esempio n. 4
0
        public void Retrieve()
        {
            var messages = new List<Message>();
            using (var client = new Pop3Client())
            {
                var appSettings = ConfigurationManager.AppSettings;
                client.Connect(appSettings["host"], 110, false);
                client.Authenticate(appSettings["user"], appSettings["pass"], AuthenticationMethod.UsernameAndPassword);
                for (var i = client.GetMessageCount(); i > 0; i--)
                {
                    var message = client.GetMessage(i);
                    messages.Add(message);
            #if (!DEBUG)
                    client.DeleteMessage(i);
            #endif
                }
            }

            _parser.Parse(messages);
        }
Esempio n. 5
0
		/// <summary>
		/// Example showing:
		///  - how to delete fetch an emails headers only
		///  - how to delete a message from the server
		/// </summary>
		/// <param name="client">A connected and authenticated Pop3Client from which to delete a message</param>
		/// <param name="messageId">A message ID of a message on the POP3 server. Is located in <see cref="MessageHeader.MessageId"/></param>
		/// <returns><see langword="true"/> if message was deleted, <see langword="false"/> otherwise</returns>
		public bool DeleteMessageByMessageId(Pop3Client client, string messageId)
		{
			// 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;
		}
    /// <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;
        }
    }
Esempio n. 7
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);
            }
        }
    }
Esempio n. 8
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);
            }
        }
    }
		public void TestDeleteMessage()
		{
			const string welcomeMessage = "+OK";
			const string okUsername = "******";
			const string okPassword = "******";
			const string deleteResponse = "+OK"; // Message was deleted
			const string quitAccepted = "+OK";
			const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n" + deleteResponse + "\r\n" + quitAccepted + "\r\n";

			Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));
			MemoryStream outputStream = new MemoryStream();

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

			client.DeleteMessage(5);

			const string expectedOutput = "DELE 5";
			string output = GetLastCommand(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			// We expected that the last command is the delete command
			Assert.AreEqual(expectedOutput, output);

			client.Disconnect();

			const string expectedOutputAfterQuit = "QUIT";
			string outputAfterQuit = GetLastCommand(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			// We now expect that the client has sent the QUIT command
			Assert.AreEqual(expectedOutputAfterQuit, outputAfterQuit);
		}
        static void Main(string[] args)
        {
            bool cnx = false;
            String logMail = "*****@*****.**", logPass = "******";
            int num = 0, band = 0;
            Message message;
            String subject;
            String notif;

            Console.WriteLine("Verificando conexión a internet...");

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface nic in nics)
            {
                if (
                    (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel) &&
                    nic.OperationalStatus == OperationalStatus.Up)
                {
                    networkIsAvailable = true;
                }
            }
            Console.Write("Conexión a Internet: ");
            Console.WriteLine(networkIsAvailable);
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);

            if (networkIsAvailable)
            {

                Console.WriteLine("Subrutina -- Lectura de Eventos Ignorar");
                Console.WriteLine("Solicitando acceso a la cuenta de correo sist_segu_2015");

                Pop3Client pop3Client = new Pop3Client();
                pop3Client.Connect("pop3.live.com", 995, true);
                pop3Client.Authenticate(logMail, logPass);
                cnx = pop3Client.Connected;

                Console.WriteLine("Solicitud de conexión a las " + DateTime.Now);
                Console.WriteLine("Conectando...");

                if (cnx == true)
                {
                    Console.WriteLine("--- Conexión exitosa ---");
                    Console.WriteLine("Se realizó conexión exitosa a las " + DateTime.Now);
                }
                else
                {
                    Console.WriteLine("--- Conexión fallida ---");
                    Console.WriteLine("Fallo de conexión a las " + DateTime.Now);
                    Console.WriteLine("Presione una tecla para salir...");
                    Console.ReadKey();
                    System.Environment.Exit(0);
                }

                num = pop3Client.GetMessageCount();
                Console.WriteLine("Usted tiene {0} correos en su bandeja", num);
                Console.WriteLine("Leyendo correos, buscando notificación IGNORAR...");
                for (int i = 1; i <= num; i++)
                {
                    message = pop3Client.GetMessage(i);
                    subject = message.ToMailMessage().Subject;
                    if (subject == "IGNORAR")
                    {
                        notif = message.ToMailMessage().Body;
                        Console.WriteLine("Contenido del correo: " + notif);
                        pop3Client.DeleteMessage(i);
                        Console.WriteLine("Se ha notificado al programa la captura del evento IGNORAR enviada por el usuario");
                        band = 1;
                    }
                    else
                    {
                        Console.WriteLine("Leyendo {0} correos...", i);
                    }
                }
                if (band == 0)
                {
                    Console.WriteLine("No se han encontrado notificaciones...");
                }

                pop3Client.Disconnect();
                Console.WriteLine("La subrutina fue desconectada a las  " + DateTime.Now);
                Console.WriteLine("Presione una tecla para salir...");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("No hay conexión a Internet, por favor verificar el inconveniente");
                Console.ReadKey();
            }
        }
Esempio n. 11
0
 //-------------------------------------------------------------------------------------------
 private string GetActivationCode()
 {
     using (Pop3Client client = new Pop3Client())
        {
             client.Connect(Helper.GetAppSetting("pop3_server"), 110, false);
             client.Authenticate(Helper.GetAppSetting("pop3_username"), Helper.GetAppSetting("pop3_password"));
             int x = client.GetMessageCount();
             for (int i = 1; i < x + 1; i++)
             {
                  Message msg = client.GetMessage(i);
                  string subj = msg.Headers.Subject;
                  if (subj == "Please activate your Weavver ID")
                  {
                       string activationCode = System.Text.Encoding.GetEncoding("utf-8").GetString(msg.FindFirstHtmlVersion().Body);
                       activationCode = activationCode.Substring(activationCode.IndexOf("Or use the following code:") + 30);
                       activationCode = activationCode.Substring(0, activationCode.IndexOf("<br>"));
                       client.DeleteMessage(i);
                       return activationCode;
                  }
             }
        }
        return null;
 }
Esempio n. 12
0
        public void TestGetMessageInfosAfterDelete()
        {
            // arrange
            const string welcomeMessage = "+OK";
            const string okUsername = "******";
            const string okPassword = "******";

            const string messageDeleteAccepted = "+OK";

            const string messageUidAccepted = "+OK";
            const string messageUid1 = "1 psycho"; // Message 1 has UID psycho
            const string messageUid2 = "3 lord"; // Message 3 has UID lord
            const string uidListEnded = ".";

            const string messageListAccepted = "+OK 2 messages (320 octets)";
            const string messageSize1 = "1 120";
            const string messageSize2 = "3 200";
            const string messageListEnd = ".";


            const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n"
                + messageDeleteAccepted + "\r\n"
                + messageUidAccepted + "\r\n" + messageUid1 + "\r\n" + messageUid2 + "\r\n" + uidListEnded + "\r\n"
                + messageListAccepted + "\r\n" + messageSize1 + "\r\n" + messageSize2 + "\r\n" + messageListEnd + "\r\n"
                ;

            Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));
            Stream outputStream = new MemoryStream();

            // act
            Pop3Client client = new Pop3Client();
            client.Connect(new CombinedStream(inputStream, outputStream));
            client.Authenticate("test", "test");

            client.DeleteMessage(2);
            List<MessageInfo> infos = client.GetMessageInfos();

            // assert
            Assert.AreEqual(2, infos.Count);

            Assert.AreEqual(1, infos[0].Number);
            Assert.AreEqual("psycho", infos[0].Identifier);
            Assert.AreEqual(120, infos[0].Size);

            Assert.AreEqual(3, infos[1].Number);
            Assert.AreEqual("lord", infos[1].Identifier);
            Assert.AreEqual(200, infos[1].Size);
        }
Esempio n. 13
0
        public string GetEmails()
        {
            var returnMessages = new List<string>();
            using (var pop3Client = new Pop3Client())
            {
                var messages = GetNewMessages(pop3Client);
                var messageCount = messages.Count();
                if (messageCount > 0)
                {
                    IMessageRepository messageRepository = new MessageRepository();
                    IMessageRecepientRepository messageRecepientRepository = new MessageRecepientRepository();
                    IMessageAttachmentRepository messageAttachmentRepository = new MessageAttachmentRepository();
                    IPermissionRepository permissionRepository = new PermissionRepository();
                    IChurchRepository churchRepository = new ChurchRepository();
                    IPersonRepository personRepository = new PersonRepository(permissionRepository, churchRepository);

                    IEmailSender emailSender = new EmailSender(messageRepository, messageRecepientRepository, messageAttachmentRepository, personRepository);

                    for (var count = 0; count < messageCount; count++)
                    {
                        var mm = messages[count].ToMailMessage();
                        var regex = new Regex(@"##([0-9]*)##");
                        var matches = regex.Matches(mm.Body);
                        if (matches.Count > 0 && matches[0].Groups.Count > 1)
                        {
                            try
                            {
                                int messageId;
                                if (int.TryParse(matches[0].Groups[1].Value, out messageId))
                                {
                                    var originalSender = messageRepository.GetSender(messageId);
                                    if (originalSender != null)
                                    {
                                        var originalReceiver = personRepository.FetchPersonIdsFromEmailAddress(mm.From.Address, originalSender.ChurchId);
                                        var fromPersonId = originalSender.PersonId;

                                        if (originalReceiver.Any())
                                        {
                                            fromPersonId = originalReceiver.First();
                                        }
                                        returnMessages.Add(string.Format("Forwarding reply from {0} for messageId {1} on to {2}", fromPersonId, messageId, originalSender.Email));
                                        emailSender.SendEmail(mm.Subject, mm.Body, Username, originalSender.Email, Username, Password, fromPersonId, originalSender.ChurchId, mm.Attachments);
                                    }
                                    pop3Client.DeleteMessage(count + 1);
                                }
                            }
                            catch (Exception errSending)
                            {
                                returnMessages.Add(errSending.Message);
                                emailSender.SendExceptionEmailAsync(errSending);
                            }
                        }
                    }
                }
            }
            if (!returnMessages.Any())
            {
                return "No replies found";
            }

            var returnMessage = returnMessages.Aggregate(string.Empty, (current, m) => current + (m + "<br/>"));
            _emailService.SendSystemEmail("Replies found", returnMessage);
            return returnMessage;
        }
        private static bool DeleteMessageByMessageId(string hostname, int port, bool useSsl, string username, string password, 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;
            }
        }
Esempio n. 15
0
		/// <summary>
		/// Example showing:
		///  - how to delete a specific message from a 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="messageNumber">
		/// The number of the message to delete.
		/// Must be in range [1, messageCount] where messageCount is the number of messages on the server.
		/// </param>
		public static void DeleteMessageOnServer(string hostname, int port, bool useSsl, string username, string password, int messageNumber)
		{
			// 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);

				// Mark the message as deleted
				// Notice that it is only MARKED as deleted
				// POP3 requires you to "commit" the changes
				// which is done by sending a QUIT command to the server
				// You can also reset all marked messages, by sending a RSET command.
				client.DeleteMessage(messageNumber);

				// When a QUIT command is sent to the server, the connection between them are closed.
				// When the client is disposed, the QUIT command will be sent to the server
				// just as if you had called the Disconnect method yourself.
			}
		}
        public IEnumerable<System.Net.Mail.MailMessage> GetPendingMessages()
        {
            using (Pop3Client client = new Pop3Client())
            {
               
                client.Connect(Host,
                    PortNumber,
                    UseSSL,
                    DEFAULT_TIMEOUT,
                    DEFAULT_TIMEOUT,
                    ValidateServerCertificate);

                client.Authenticate(Username, Password);

                // Obtém o número de mensagens na caixa de entrada
                int messageCount = client.GetMessageCount();

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

                // Mensagens são numeradas a partir do número 1
                for (int i = 1; i <= messageCount; i++)
                {
                    Message _mensagem = client.GetMessage(i);
                    
                    MailMessage m = _mensagem.ToMailMessage();
                    MessageHeader headers = _mensagem.Headers;
                    
                    foreach (var mailAddress in headers.Bcc)
                        m.Bcc.Add(mailAddress.MailAddress);

                    foreach (var mailAddress in headers.Cc)
                        m.CC.Add(mailAddress.MailAddress);

                    m.Headers.Add("Date", headers.Date);
                    m.From = headers.From.MailAddress;

                    yield return m;

                    if (OnMessageRead != null)
                    {
                        OnMessageReadEventArgs e = new OnMessageReadEventArgs();
                        OnMessageRead(this, e);
                        if (e.Cancel)
                            continue;
                    }
                    try
                    {
                        client.DeleteMessage(i);
                    }
                    catch (PopServerException)
                    { 
                        //Ignore
                    }
                }
            }
        }
        private static bool DeleteMessageByMessageId(Pop3Client client, string messageId)
        {
            var messageCount = client.GetMessageCount();

            for (var messageItem = messageCount; messageItem > 0; messageItem--)
            {
                if (client.GetMessageHeaders(messageItem).MessageId != messageId) continue;
                client.DeleteMessage(messageItem);
                return true;
            }

            return false;
        }
Esempio n. 18
0
        public void RetrieveEmails(string EmailAddress, string Password, string ConnString, string DeleteMessage, string HostName, int Port, bool UseSsl, bool sendreceivedemail, bool SendOverDueReceivedEmail)
        {
            Pop3Client client = new Pop3Client();

            client.Connect(HostName, Port, UseSsl);//the type of server

            client.Authenticate(EmailAddress, Password);//connects to the inbox we want to get the emails from

            int Count = client.GetMessageCount();//gets the message count for the inbox of the above email

            for (int i = 1; i <= Count; i++)//loops through the messages in the inbox
            {
                OpenPop.Mime.Message message = client.GetMessage(i);//gets the message 

                string email = message.Headers.From.Address.ToString();//this gets the email address

                string subject = message.Headers.Subject.ToString();//this gets the subject

                string Parent = getBetween(subject, "(", ")");

                int parent;

                try
                {
                    parent = Convert.ToInt32(Parent);
                }

                catch
                {
                    parent = 0;
                }

                string body = message.FindFirstPlainTextVersion().GetBodyAsText();//this gets the body

                int ticketid = AddEmailToDatabase(ConnString, email, subject, body, parent);//this add the email message to the database and returns its ticketid

                if (parent == 0)
                {
                    if (sendreceivedemail == true)
                    {
                        SendReceivedEmail(ConnString, email, EmailAddress, Password, ticketid);//sends an email back saying we received there email
                    }
                }

                foreach (OpenPop.Mime.MessagePart emailattachment in message.FindAllAttachments())//this loops through all the attachments for a message
                {
                    string OriginalFileName = emailattachment.FileName;//gets the original file name of the attachment

                    string ContentID = emailattachment.ContentId;//if this is set then the attachment is inline.

                    string ContentType = emailattachment.ContentType.MediaType;//type of attachment pdf, jpg, png, etc.

                    byte[] Content = emailattachment.Body;//gets the body of the attachment as a byte[]

                    using (MemoryStream MS = new MemoryStream(Content))//puts the Content[] into a memory stream
                    {

                        Image im = Image.FromStream(MS, true, true);//Image from the memorystream

                        int sourceWidth = im.Width;//the original width of the image

                        int sourceHeight = im.Height;//the original height of the image

                        float nPercent = 0;

                        float nPercentW = 0;

                        float nPercentH = 0;
                        //the following code checks which is larger the height or width and then resizes the image accordingly
                        nPercentW = ((float)900 / (float)sourceWidth);

                        nPercentH = ((float)900 / (float)sourceHeight);

                        if (nPercentH < nPercentW)
                            nPercent = nPercentH;
                        else
                            nPercent = nPercentW;

                        int destWidth = (int)(sourceWidth * nPercent);
                        int destHeight = (int)(sourceHeight * nPercent);

                        Bitmap b = new Bitmap(destWidth, destHeight);
                        Graphics g = Graphics.FromImage((Image)b);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        g.DrawImage(im, 0, 0, destWidth, destHeight);
                        g.Dispose();

                        MemoryStream m = new MemoryStream();

                        b.Save(m, ImageFormat.Jpeg);

                        Content = m.ToArray();
                    }

                    AddAttachmentToDatabase(ConnString, ticketid, OriginalFileName, Content);//adds the attachment to the database

                    //write the attachment to the disk
                    //System.IO.File.WriteAllBytes("C:/Users/David/Documents/Visual Studio 2012/Projects/GetEmails/GetEmails/Attachments/" +ticketid+ OriginalFileName, emailattachment.Body);//overwrites MessagePart.Body with attachment

                    //string attachment = "~/Attachments/" + ticketid + OriginalFileName;

                    //AddAttachmentToDatabase(ticketid,attachment);

                }
            }

            if (DeleteMessage == "Yes")//checks whether to delete the message from the inbox
            {
                for (int i = Count; i > 0; i--)
                {
                    client.DeleteMessage(i);//deletes the messages from the inbox
                }

                client.Dispose();
            }
            if (SendOverDueReceivedEmail == true)
            {
                SendOverDueEmail(ConnString, EmailAddress, Password); //This will send a message to the user notifying them of a ticket that has not been opened after 3 hours

            }
        }
Esempio n. 19
0
        private void GetMails(MailboxInfo info)
        {
            try
            {
                using (var client = new Pop3Client())
                {
                    //Get Zabbix metrics
                    var stopwatch = new Stopwatch();
                    stopwatch.Start();
                    //Get mail count
                    client.Connect(info.Hostname, info.Port, false);
                    client.Authenticate(info.User, info.Password);
                    stopwatch.Stop();

                    //Send it to Zabbix
                    Functions.Zabbix.SendData(new ZabbixItem { Host = _config.HostKey, Key = info.Type + _config.TimingKey, Value = stopwatch.ElapsedMilliseconds.ToString() });
                    Functions.Log.Debug("Send [{0}] timing to Zabbix: connected to '{1}' as '{2}', timing {3}ms", info.Type, info.Hostname, info.User, stopwatch.ElapsedMilliseconds);

                    var count = client.GetMessageCount();
                    if (count == 0)
                        return;

                    Functions.Log.Debug("We've got new {0} messages in '{1}'", count, info.User);
                    //Send messages to sorting block
                    for (var i = 0; i < count; i++)
                    {
                        try
                        {
                            var mailInfo = new MessageInfo
                            {
                                IsSpam = false,
                                Mail = client.GetMessage(i + 1),
                                Type = MessageType.UNKNOWN,
                                Subtype = null,
                                Recipient = null,
                                Mailbox = info
                            };
                            Functions.Log.Debug("Download message from '{0}'. Size: {1}b", info.User, mailInfo.Mail.RawMessage.Length);
                            while (!_sortMailDataBlock.Post(mailInfo))
                                Thread.Sleep(500);

                            //Save every mail to archive
                            Functions.Log.Debug("Archive message");
                            Functions.Archive.Info(Functions.MessageToString(mailInfo.Mail));
                        }
                        catch (Exception ex)
                        {
                            Functions.Log.Error("Parse email error: {0}", ex.Message);
                            Functions.ErrorsCounters[info.Type].Increment();

                            //Archive mail anyway
                            Functions.Log.Debug("Archive message");
                            Functions.Archive.Info(Encoding.Default.GetString(client.GetMessageAsBytes(i + 1)));
                        }

                        if (_config.DeleteMail)
                            client.DeleteMessage(i + 1);

                        if (_stopPipeline)
                            break;
                    }
                    Functions.Log.Debug("Done with '{0}'", info.User);
                }
            }
            catch (Exception ex)
            {
                Functions.Log.Error("General error - type: {0}, message: {1}", ex, ex.Message);
                Functions.ErrorsCounters[info.Type].Increment();
            }
        }