Exemplo n.º 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();
        }
    }
Exemplo n.º 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));
            }
        }
Exemplo n.º 3
1
		/// <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;
			}
		}
Exemplo n.º 4
1
        protected override void ExecuteCheck(out bool isAlive, out string message)
        {
            isAlive = false;
            message = null;

            try
            {
                using (var client = new Pop3Client())
                {
                    client.Connect(_settings["Host"], 110, false);

                    client.Authenticate(_settings["Username"], _settings["Password"]);

                    client.GetMessageCount();
                }

                isAlive = true;
            }
            catch (Exception e)
            {
                message = e.Message;
            }
        }
Exemplo n.º 5
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});
                }
            }
        }
Exemplo n.º 6
0
        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));
                }
            }
        }
        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;
            }
        }
Exemplo n.º 8
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);
                              }
                         }
                    }
               }
        }
Exemplo n.º 9
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;
            }
        }
Exemplo n.º 10
0
        //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;
        }
Exemplo n.º 11
0
        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;
        }
Exemplo n.º 12
0
        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
Exemplo n.º 13
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));
            }
        }
Exemplo n.º 14
0
 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
     {
     };
 }
Exemplo n.º 15
0
        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;
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
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;
		}
Exemplo n.º 18
0
        public void Execute(IJobExecutionContext context)
        {

            _logger.Debug("RetrievePop3DataJob");

            var settings = Properties.Settings.Default.Pop3Settings;


            using (var client = new Pop3Client())
            {
                try
                {
                    // Connect to the server
                    client.Connect(settings.HostName, settings.Port, settings.UseSSL);

                    // Authenticate ourselves towards the server
                    client.Authenticate(settings.UserName, settings.Password);

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

                    // 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--)
                    {
                        var message = client.GetMessage(i).ToMailMessage();

                        _logger.Debug($"Retrieve message {i}");

                        //client.DeleteMessage(i);
                        //_logger.Debug($"Delete message {i}");
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(this, ex);
                }
            }
        }
Exemplo n.º 19
0
        public static List<Message> GetAllMails(string hostname, int port, bool useSsl, string username, string password)
        {
            using(Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);

                client.Authenticate(username, password);

                int messageCount = client.GetMessageCount();

                Debug.WriteLine(messageCount);

                List<Message> allMessages = new List<Message>(messageCount);

                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                    Debug.WriteLine(client.GetMessage(i).MessagePart);
                }
                return allMessages;
            }
        }
Exemplo n.º 20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Pop3Client pop = new Pop3Client();
            pop.Connect("email-ssl.com.br", 995,true);
            pop.Authenticate("*****@*****.**", "yourpassword");
            if (pop.Connected)
            {
                Int32 tot = pop.GetMessageCount();
                lblTotMessage.Text = "Conexão feito. Total Mensagem: " + tot.ToString();
               
                DataTable datatb = new DataTable();
                datatb.Columns.Add("MessageNumber");
                datatb.Columns.Add("From");
                datatb.Columns.Add("Subject");
                datatb.Columns.Add("DateSent");
                int counter = 0;
                for (int i = 1; i < tot; i++)
                {

                    Message message = pop.GetMessage(i);
                    datatb.Rows.Add();
                    datatb.Rows[datatb.Rows.Count - 1]["MessageNumber"] = i;
                    datatb.Rows[datatb.Rows.Count - 1]["Subject"] = message.Headers.Subject;
                    datatb.Rows[datatb.Rows.Count - 1]["DateSent"] = message.Headers.DateSent;
                    counter++;
                    if (counter > 20)
                    {
                        break;
                    }
                }
                
                gvTicket.DataSource = datatb;
                gvTicket.DataBind();
                 
            }

         
        }
Exemplo n.º 21
0
        public override void onPageLoad()
        {
            Pop3Client client = new Pop3Client();
            client.Connect("pop3.live.com", 995, true);
            client.Authenticate("*****@*****.**", "sedona72894");

            // 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--)
            {
                if(i == messageCount - 10)
                    break;

                echo(client.GetMessage(i).ToMailMessage().Subject + "<br />");
            }
        }
Exemplo n.º 22
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;
 }
Exemplo n.º 23
0
        /// <summary>
        /// получаем список сообщений из ящика
        /// </summary>
        /// <param name="hostname">хост. Например, pop.yandex.ru</param>
        /// <param name="port">порт. Например, 110</param>
        /// <param name="useSsl">использовать ssl</param>
        /// <param name="username">логин</param>
        /// <param name="password">пароль</param>
        /// <returns>список емейлов</returns>
        public static List<OpenPop.Mime.Message> FetchAllEmailMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using(Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);
                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.
                for(int i = 1; i <= messageCount; i++)
                    allMessages.Add(client.GetMessage(i));

                // Now return the fetched messages
                return allMessages;
            }
        }
Exemplo n.º 24
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;
        }
    }
Exemplo n.º 25
0
        /// <summary>
        /// Método DescargarCorreos.
        /// Permite descargar los correos de una casilla de correo del tipo Gmail.
        /// </summary>
        /// <param name="pCuenta">Cuenta para descargar correos</param>
        /// <returns>Lista de emails descargados</returns>
        public override List<EmailDTO> DescargarCorreos(CuentaDTO pCuenta)
        {
            List<EmailDTO> iListaCorreosDescargados = new List<EmailDTO>();
            Pop3Client iPop = new Pop3Client();
            int iCantidadMensajes;
            string iIDMensaje;
            try
            {
                iPop.Connect("pop.gmail.com", 995, true);
                iPop.Authenticate(pCuenta.Direccion, pCuenta.Contraseña);
                iCantidadMensajes =  iPop.GetMessageCount();
                string iCuerpo = "";
                string iTipoCorreo = "";
                List<String> iDestino = new List<String>();
                List<String> iCC = new List<String>();
                List<String> iCCO = new List<String>();
                List<MessagePart> iListaAdjuntos = new List<MessagePart>();
                for (int i = iCantidadMensajes; i > 0; i--)
                {
                    
                    iDestino.Clear();
                    iCC.Clear();
                    iCCO.Clear();
                    
                    Message iMensaje = iPop.GetMessage(i);
                    iIDMensaje = iPop.GetMessageHeaders(i).MessageId;
                    if (iIDMensaje == null)
                    {
                        iIDMensaje = "";
                    }
                    MessagePart iTexto = iMensaje.FindFirstPlainTextVersion();
                    if (iTexto != null)
                    {
                        iCuerpo = iTexto.GetBodyAsText();
                    }
                    else
                    {
                        MessagePart iHTML = iMensaje.FindFirstHtmlVersion();
                        if (iHTML != null)
                        {
                            iCuerpo = iHTML.GetBodyAsText();
                        }
                    }
                    if (iMensaje.Headers.From.Address == pCuenta.Direccion)
                    {
                        iTipoCorreo = "Enviado";
                    }
                    else
                    {
                        iTipoCorreo = "Recibido";
                    }

                    foreach (RfcMailAddress direccionCorreo in iMensaje.Headers.To)
                    {
                        iDestino.Add(direccionCorreo.Address);
                    }

                    foreach (RfcMailAddress direccionCC in iMensaje.Headers.Cc)
                    {
                        iCC.Add(direccionCC.Address);
                    }

                    foreach (RfcMailAddress direccionCCO in iMensaje.Headers.Bcc)
                    {
                        iCCO.Add(direccionCCO.Address);
                    }
                    EmailDTO iNuevoMail = new EmailDTO(
                            pCuenta.ID,
                            iTipoCorreo,
                            iMensaje.Headers.From.Address,
                            iDestino,
                            iMensaje.Headers.Subject,
                            iCuerpo,
                            iMensaje.Headers.DateSent.ToString(),
                            true,
                            iCC,
                            iCCO,
                            iIDMensaje,
                            "No leído"
                        );
                    iListaCorreosDescargados.Add(iNuevoMail);
                }
            }
            catch (InvalidLoginException)
            {
                throw new ServiciosCorreoException("No se puede actualizar la bandeja de la cuenta " + pCuenta.Direccion + ". Hubo un problema en el acceso");
            }
            catch (PopServerNotFoundException)
            {
                throw new ServiciosCorreoException("No se puede actualizar la bandeja de la cuenta " + pCuenta.Direccion + ". Hubo un error en el acceso al servidor POP3 de Gmail");
            }
            catch (Exception)
            {
                throw new ServiciosCorreoException("No se puede actualizar la bandeja de la cuenta " + pCuenta.Direccion + ".");
            }
            return iListaCorreosDescargados;
            
        }
Exemplo n.º 26
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; }
        }
Exemplo n.º 27
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

            }
        }
Exemplo n.º 28
0
        public static List<MailParts> CheckInbox(ref string resultTopic, ref string resultMsg)
        {
            if (resultMsg == null) throw new ArgumentNullException("resultMsg");
            //Dictionary<int, Message> messages = new Dictionary<int, Message>();
            Pop3Client pop3Client = new Pop3Client();
            List<MailParts> querys = new List<MailParts>();

            try
            {
                if (pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }

                pop3Client.Connect(Settings.POPserver, Settings.POPport, true);
                pop3Client.Authenticate(Settings.EmailUser, Settings.EmailPass);

                int count = pop3Client.GetMessageCount();

                for (int i = count; i >= 1; i -= 1)
                {
                    try
                    {
                        Message message = pop3Client.GetMessage(i);
                        //messages.Add(i, message);

                        if (message.Headers.Subject.Equals("Aramis-IT: Sending query"))
                        {
                            if (message.MessagePart != null &&
                                message.MessagePart.IsText)
                            {
                                string[] parts = message.MessagePart.GetBodyAsText().Split(
                                    new[] { ParameterTag },
                                    StringSplitOptions.RemoveEmptyEntries);
                                MailParts mail = new MailParts { Parameter = new List<SQLiteParameter>() };
                                bool isFirst = true;

                                foreach (string part in parts)
                                {
                                    if (!isFirst)
                                    {
                                        string[] p = part.Split('=');
                                        mail.Parameter.Add(new SQLiteParameter(p[0], p[1].Replace("\r\n", "")));
                                    }
                                    else
                                    {
                                        isFirst = false;
                                        mail.Command = part;
                                    }
                                }

                                querys.Add(mail);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                    }
                }

            }
            catch (InvalidLoginException)
            {
                resultTopic = "POP3 Server Authentication";
                resultMsg = "The server did not accept the user credentials!";
                return null;
            }
            catch (PopServerNotFoundException)
            {
                resultTopic = "POP3 Retrieval";
                resultMsg = "The server could not be found";
                return null;
            }
            catch (PopServerLockedException)
            {
                resultTopic = "POP3 Account Locked";
                resultMsg = "The mailbox is locked. It might be in use or under maintenance.";
                return null;
            }
            catch (LoginDelayException)
            {
                resultTopic = "POP3 Account Login Delay";
                resultMsg = "Login not allowed. Server enforces delay between logins.";
                return null;
            }
            catch (Exception e)
            {
                resultTopic = "POP3 Retrieval";
                resultMsg = "Error occurred retrieving mail. " + e.Message;
                return null;
            }
            finally
            {
                if(pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }
            }

            //foreach (Message msg in messages.Values)
            //{
            //    if (msg.MessagePart != null &&
            //        msg.MessagePart.MessageParts != null &&
            //        msg.MessagePart.MessageParts.Count >= 1 &&
            //        msg.MessagePart.MessageParts[0].IsText)
            //    {
            //        string body = msg.MessagePart.MessageParts[0].GetBodyAsText();
            //        //querys.Add(body);
            //    }
            //}

            return querys;
        }
		public void TestGetMessageCount()
		{
			const string welcomeMessage = "+OK";
			const string okUsername = "******";
			const string okPassword = "******";
			const string statCommandResponse = "+OK 5 10"; // 5 Messages with total size of 10 octets
			const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n" + statCommandResponse + "\r\n";
			Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));

			Stream outputStream = new MemoryStream();

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

			int numberOfMessages = client.GetMessageCount();

			// We expected 5 messages
			Assert.AreEqual(5, numberOfMessages);
		}
        /// <summary>
        /// use the pop client to get the latest message 
        /// </summary>
        /// <returns></returns>
        private bool GetLastestUpload_POP()
        {
            //return true;
            try
            {
                using (Pop3Client client = new Pop3Client())
                {

                    //string hostname = "pop.gmail.com";
                    //int port = 995;
                    //bool useSsl = true;
                    //string username = "******";
                    //string password = "******";

                    // Connect to the server

                    int portNo = 0;

                    if (int.TryParse(_popPort, out portNo))
                    {
                        client.Connect(_popHost, portNo, true);

                        // Authenticate ourselves towards the server
                        client.Authenticate(_icmsEmailAddress, _smtpPassword);

                        string fileName = string.Empty;
                        // We know the message contains an attachment with the name "useful.pdf".
                        // We want to save this to a file with the same name
                        //for (int i = client.GetMessageCount(); i == 0; i--)
                        //{
                        int latestMessage = client.GetMessageCount();
                        Message message = client.GetMessage(latestMessage);
                        MMDAutomation.Messageing.MessageLog msgLog = new MessageLog(message.Headers.MessageId, message.Headers.DateSent, _sqlConnectionString);
                        if (message.Headers.Subject.Contains(_emailSubject))
                        {
                            if (!msgLog.CheckMessageId())
                            {

                                //message not found -- process file
                                foreach (MessagePart attachment in message.FindAllAttachments())
                                {
                                    fileName = attachment.FileName;
                                    if (fileName.Split('.')[1].Equals("xlsx")) //attachment.FileName.Equals(@"WADALAOR.xlsx"))
                                    {
                                        // Save the raw bytes to a file
                                        //string fileLocation = @"C:\Users\Marnee Dearman\Documents\SK Auto\ICMS Excel Downloads\";
                                        _attachment += fileName.Replace(" ", "");
                                        System.IO.File.WriteAllBytes(_attachment, attachment.Body);
                                        LogUpload("File downloaded at " + DateTime.Now);
                                    }
                                }

                                msgLog.LogMessageId();
                            }
                        }
                        //client.DeleteMessage(latestMessage);

                    }
                    //client.Dispose();
                    //}
                    return true;
                }
            }
            catch (Exception ex)
            {
                AutoUploadLog log = new AutoUploadLog("GetLatesUpload_POP: " + ex.Message, _sqlConnectionString);
                return false;
            }
        }
Exemplo n.º 31
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 void ProcessNewMessages(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 don't want to download all messages
                // List<Message> allMessages = new List<Message>(messageCount);
                List<string> uids = client.GetMessageUids();

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                for (int i = 1; i <= messageCount; i++)
                {
                    String uid = client.GetMessageUid(i);
                    if (seenUids.Contains(uid))
                    {
                        continue;
                    }

                    Message m = client.GetMessage(i);
                    if (m.MessagePart != null)
                    {
                        if (m.MessagePart.MessageParts != null)
                        {
                            for (int j = 0; j < m.MessagePart.MessageParts.Count; j++)
                            {
                                //if (m.MessagePart.MessageParts[j].Body != null)
                                //{
                                //    System.Console.Write(ASCIIEncoding.ASCII.GetString(m.MessagePart.MessageParts[j].Body));
                                //}

                                if (((m.MessagePart.MessageParts[j].IsAttachment) &&
                                    (m.MessagePart.MessageParts[j].FileName == "invite.ics")) ||
                                    ((m.MessagePart.MessageParts[j].ContentType != null) &&
                                     (m.MessagePart.MessageParts[j].ContentType.MediaType.StartsWith("text/calendar"))))
                                {
                                    //System.Console.Write(ASCIIEncoding.ASCII.GetString(m.MessagePart.MessageParts[j].Body));
                                    List<String> lines = ParseICalendar(m.MessagePart.MessageParts[j].Body);

                                    // Then find the relevant lines.
                                    // Make sure this is a VCALENDAR attachment.
                                    if ((lines != null) && lines[0].StartsWith("BEGIN:VCALENDAR"))
                                    {
                                        Meeting meeting = new Meeting();
                                        ExtractAttributes(lines, meeting);
                                        String json = meeting.ToJson();
                                        System.Console.WriteLine("Processing Message: " + uid);
                                        System.Console.WriteLine("JSON: " + json);
                                        seenUids.Add(uid);
                                        //PostJsonToWebServer(json);
                                    }
                                }
                            }
                        }
                    }
                    //System.Console.Write(ASCIIEncoding.ASCII.GetString(m.MessagePart.MessageParts[0].Body));
                    //allMessages.Add(m);
                }
            }
        }
Exemplo n.º 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);
            }
        }