Пример #1
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            _enableSettingControls(false, false);
            if (!_tryOauth())
            {
                _enableSettingControls(true, false);
                return;
            }

            if (ComboBoxAuthType.SelectedIndex == (int)ServerAuthType.AuthXOAUTH2)
            {
                textUser.Text     = _oauthWrapper.OauthProvider.UserEmail;
                textPassword.Text = _oauthWrapper.OauthProvider.AccessToken;
            }

            if (!_validateInput())
            {
                _enableSettingControls(true, false);
                return;
            }

            _enableSettingControls(false, true);

            // UIDL is the identifier of every email on POP3/IMAP4/Exchange server, to avoid retrieve
            // the same email from server more than once, we record the email UIDL retrieved every time
            // if you delete the email from server every time and not to leave a copy of email on
            // the server, then please remove all the function about uidl.
            // UIDLManager wraps the function to write/read uidl record from a text file.
            UIDLManager oUIDLManager  = new UIDLManager();
            bool        _isUidlLoaded = false;

            try
            {
                // For evaluation usage, please use "TryIt" as the license code, otherwise the
                // "Invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
                // "Trial version expired" exception will be thrown.
                MailClient client = new MailClient("TryIt");

                // Catching the following events is not necessary,
                // just make the application more user friendly.
                // If you use the object in asp.net/windows service or non-gui application,
                // You need not to catch the following events.
                // To learn more detail, please refer to the code in EAGetMail EventHandler region
                client.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                client.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
                client.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
                client.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
                client.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                _isCancelOperation = false;
                textStatus.Text    = "Connecting ...";

                // generate a log file for debug
                // client.LogFileName = string.Format("{0}\\log.txt", _currentPath);

                MailServer server = _buildServer();
                client.Connect(server);

                string localInbox = _createLocalInbox();

                // load existed uidl records to UIDLManager
                string uidlfile = string.Format("{0}\\{1}", localInbox, _uidlFile);
                oUIDLManager.Load(uidlfile);
                _isUidlLoaded = true;

                _setMailRange(ref client);

                textStatus.Text = "Retrieveing email list ...";
                MailInfo[] infos = client.GetMailInfos();
                textStatus.Text = string.Format("Total {0} email(s)", infos.Length);

                if (ComboBoxDateRange.SelectedIndex == 0)
                {
                    // Remove the local uidl that is not existed on the server,
                    // we only synchronize it with uidl of all emails in current mail folder
                    oUIDLManager.SyncUIDL(server, infos);
                    oUIDLManager.Update();
                }

                for (int i = 0; i < infos.Length; i++)
                {
                    pgBar.Maximum = 100;
                    pgBar.Minimum = 0;
                    pgBar.Value   = 0;

                    textStatus.Text = string.Format("Checking {0}/{1}...", i + 1, infos.Length);

                    MailInfo info = infos[i];
                    if (oUIDLManager.FindUIDL(server, info.UIDL) != null)
                    {
                        //this email has been downloaded before.
                        continue;
                    }

                    textStatus.Text = string.Format("Retrieving {0}/{1}...", i + 1, infos.Length);

                    Mail mail = client.GetMail(info);

                    string fileName     = _generateFileName(i + 1);
                    string fullFileName = string.Format("{0}\\{1}", localInbox, fileName);
                    mail.SaveAs(fullFileName, true);

                    _addNewMailToListView(ref mail, fullFileName);
                    mail.Clear();

                    LabelTotal.Text = string.Format("Total {0} email(s)", ListViewMail.Items.Count);

                    // If retrieve only new emails, after we retrieved it, mark it as read,
                    // With this feature, you don't have to UIDLManager to prevent duplicated emails.
                    if (chkNewOnly.Checked && ComboBoxProtocol.SelectedIndex != (int)ServerProtocol.Pop3)
                    {
                        client.MarkAsRead(info, true);
                    }

                    if (chkLeaveCopy.Checked)
                    {
                        // Add the email uidl to uidl file to avoid we retrieve it next time.
                        oUIDLManager.AddUIDL(server, info.UIDL, fileName);
                    }
                    else
                    {
                        textStatus.Text = string.Format("Deleting {0}...", i + 1);
                        client.Delete(info);

                        // Remove UIDL from local uidl file.
                        oUIDLManager.RemoveUIDL(server, info.UIDL);
                    }
                }

                // Delete method just mark the email as deleted,
                // Quit method expunge the emails from server exactly.
                client.Quit();

                // Update the uidl list to local uidl file and then we can load it next time.
                oUIDLManager.Update();
                textStatus.Text = "Completed";
            }
            catch (Exception ep)
            {
                if (_isUidlLoaded)
                {
                    // Update the uidl list to local uidl file and then we can load it next time.
                    oUIDLManager.Update();
                }

                MessageBox.Show(ep.Message);
                textStatus.Text = ep.Message;
            }

            _enableSettingControls(true, false);
        }
Пример #2
0
        private void btndescargarcorreo_Click(object sender, EventArgs e)
        {
            try
            {
                string mensajError = "";
                if (InfoCuenta == null)
                {
                    mail_Cuentas_Correo_Bus         bus_correo   = new mail_Cuentas_Correo_Bus();
                    List <mail_Cuentas_Correo_Info> lista_Correo = new List <mail_Cuentas_Correo_Info>();
                    lista_Correo = bus_correo.consultar(ref mensajError);
                    InfoCuenta   = lista_Correo.FirstOrDefault(q => q.direccion_correo == dir_correo);
                }

                if (InfoCuenta.ServidorCorreoEntrante.Length == 0 || InfoCuenta.Usuario.Length == 0 || InfoCuenta.Password.Length == 0)
                {
                    MessageBox.Show("Por favor ingrese servidor, usuario y contraseña.");
                    return;
                }
                // cargo los ID de mensaje para no tener q ir a la DB
                lista_codMensajeId_Existentes = new List <string>();
                lista_codMensajeId_Existentes = Bus_Mensaje.consultar_CodMail_Existentes();
                btndescargarcorreo.Enabled    = false;
                btnCancel.Enabled             = true;
                lista_Mensaje = new List <mail_Mensaje_Info>();
                string mensajeError = "";

                ServerAuthType authType = ServerAuthType.AuthLogin;

                if (InfoCuenta.Tipo_Authenticacion == "APOP")
                {
                    authType = ServerAuthType.AuthCRAM5;
                }
                else if (InfoCuenta.Tipo_Authenticacion == "NTLM")
                {
                    authType = ServerAuthType.AuthNTLM;
                }
                // ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex;
                ServerProtocol protocol = new ServerProtocol();
                if (InfoCuenta.TipoCuenta == "POP3")
                {
                    protocol = ServerProtocol.Pop3;
                }
                if (InfoCuenta.TipoCuenta == "IMAP4")
                {
                    protocol = ServerProtocol.Imap4;
                }
                if (InfoCuenta.TipoCuenta == "EXCHA_WEB_SER")
                {
                    protocol = ServerProtocol.ExchangeEWS;
                }
                if (InfoCuenta.TipoCuenta == "EXCHA_WEB_DAV")
                {
                    protocol = ServerProtocol.ExchangeWebDAV;
                }


                usa_sll = (InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo == null) ? false : (Boolean)InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo;

                MailServer oServer = new MailServer(InfoCuenta.ServidorCorreoEntrante, InfoCuenta.Usuario, InfoCuenta.Password,
                                                    usa_sll, authType, protocol);



                // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el
                // será lanzado  excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego
                // "versión de prueba expiró" se lanzará una excepción.

                MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F");

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EAGetMail EventHandler region

                oClient.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                oClient.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
                oClient.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
                oClient.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
                oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                bool bMantener_copia_correo = (InfoCuenta.Guardar_1_copia_de_corre_en_server_mail == null) ? false : (Boolean)InfoCuenta.Guardar_1_copia_de_corre_en_server_mail;

                UIDLManager oUIDLManager = new UIDLManager();

                try
                {
                    // Carga existían registros UIDL a UIDLManager
                    string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
                    oUIDLManager.Load(uidlfile);

                    string mailFolder = String.Format("{0}\\inbox", m_curpath);
                    if (!Directory.Exists(mailFolder))
                    {
                        Directory.CreateDirectory(mailFolder);
                    }

                    m_bcancel      = false;
                    lblStatus.Text = "Conectando ...";
                    oClient.Connect(oServer);
                    MailInfo[] infos = oClient.GetMailInfos();
                    lblStatus.Text = String.Format("Total {0} email(s)", infos.Length);

                    // Eliminar el uidl local que no se existía en el servidor.
                    oUIDLManager.SyncUIDL(oServer, infos);
                    oUIDLManager.Update();

                    int count = infos.Length;

                    if (count > 0)
                    {
                        lista_Mensaje = new List <mail_Mensaje_Info>();
                    }

                    int CountError = 0;

                    for (int i = 0; i < count; i++)
                    {
                        MailInfo info = infos[i];
                        CountError = i;
                        //if (i == 2587) { MessageBox.Show(""); }


                        //verificar en base NO debo ir a la base uno a uno sino se hace muy largo
                        if (lista_codMensajeId_Existentes.Contains(info.UIDL) == false)
                        {
                            lblStatus.Text = String.Format("Retrieving {0}/{1}...", info.Index, count);
                            Mail            oMail = oClient.GetMail(info);
                            System.DateTime d     = System.DateTime.Now;
                            System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                            string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                            string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);


                            try//try1
                            {
                                oMail.SaveAs(fileName, true);

                                conta = 0;
                                conta = oMail.To.ToList().Count();
                                sec   = 0;
                                foreach (var itemTo in oMail.To.ToList())
                                {
                                    sec = sec + 1;
                                    if (sec != conta)
                                    {
                                        para += itemTo.Address + "; ";
                                    }
                                    else
                                    {
                                        para += itemTo.Address;
                                    }
                                }

                                conta = 0;
                                conta = oMail.Cc.ToList().Count();
                                sec   = 0;
                                foreach (var itemCopia in oMail.Cc.ToList())
                                {
                                    sec = sec + 1;
                                    if (sec != conta)
                                    {
                                        CC += itemCopia.Address + "; ";
                                    }
                                    else
                                    {
                                        CC += itemCopia.Address;
                                    }
                                }
                            }
                            catch (Exception EX)
                            {
                                MessageBox.Show(EX.Message + " try 1");
                            }


                            try//try2
                            {
                                infoMensaje        = new mail_Mensaje_Info();
                                infoMensaje.Asunto = oMail.Subject;
                                infoMensaje.Asunto_texto_mostrado = oMail.Subject;
                                // infoMensaje.codMensajeId = MessageID;
                                infoMensaje.codMensajeId = info.UIDL;

                                infoMensaje.fileName      = fileName;
                                infoMensaje.Para          = para;
                                infoMensaje.Para_CC       = CC;
                                infoMensaje.Fecha         = oMail.ReceivedDate;
                                infoMensaje.Texto_mensaje = oMail.TextBody;

                                infoMensaje.Tiene_Adjunto = oMail.Attachments.Count() == 0 ? false : true;

                                if (Convert.ToString(oMail.Priority) == "Normal")
                                {
                                    infoMensaje.Prioridad = 0;
                                }
                                if (Convert.ToString(oMail.Priority) == "Alta")
                                {
                                    infoMensaje.Prioridad = 1;
                                }
                                if (Convert.ToString(oMail.Priority) == "Baja")
                                {
                                    infoMensaje.Prioridad = -1;
                                }

                                infoMensaje.Leido      = false;
                                infoMensaje.Respondido = false;
                                infoMensaje.No_Leido   = false;

                                infoMensaje.mail_remitente = dir_correo;
                                infoMensaje.Eliminado      = false;
                                infoMensaje.IdTipo_Mensaje = eTipoMail.Buzon_Ent;


                                infoMensaje.IdCuenta = IdCuenta;

                                foreach (var itemAdju in oMail.Attachments)
                                {
                                    mail_Mensaje_Archi_Adjunto_Info infoAdju = new mail_Mensaje_Archi_Adjunto_Info();

                                    string nomAdju = itemAdju.Name;

                                    string extAdj = Path.GetExtension(nomAdju);
                                    if (extAdj.ToUpper() == ".PDF" || extAdj.ToUpper() == ".XML")
                                    {
                                        infoAdju.extensionArchivo  = extAdj;
                                        infoAdju.Archivo_adjunto   = itemAdju.Content;
                                        infoAdju.descripcion_archi = itemAdju.Name;

                                        infoMensaje.list_Archivos_Adjuntos.Add(infoAdju);
                                    }
                                }

                                infoMensaje.Archivo_correo = System.IO.File.ReadAllBytes(infoMensaje.fileName);


                                Bus_Mensaje.GrabarMensajeDB(infoMensaje, ref mensajeError);
                                //lista_Mensaje.Add(infoMensaje);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message + " try 2");
                            }


                            oMail.Clear();

                            // si lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count);

                            if (bMantener_copia_correo)
                            {
                                // añadir el uidl correo electrónico a uidl archivo para evitar recuperamos la próxima vez.
                                oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                            }
                        }
                    }

                    if (!bMantener_copia_correo)
                    {
                        lblStatus.Text = "Borrando ...";
                        for (int i = 0; i < count; i++)
                        {
                            oClient.Delete(infos[i]);
                            // Eliminar UIDL de archivo uidl local.
                            oUIDLManager.RemoveUIDL(oServer, infos[i].UIDL);
                        }
                    }
                    // Eliminar método sólo marcar el correo electrónico como eliminado,
                    // Salir método puro los mensajes de correo electrónico desde el servidor exactamente.
                    oClient.Quit();

                    //if (lista_Mensaje.Count() == 0)
                    //{
                    //    MessageBox.Show("No existen Correos de Entrada Nuevos");
                    //    btndescargarcorreo.Enabled = true;
                    //    btnCancel.Enabled = false;
                    //    return;
                    //}
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                    BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                }

                // Actualizar la lista uidl de archivo uidl local y luego podemos cargar la próxima vez.
                oUIDLManager.Update();

                lblStatus.Text             = "Completed";
                pgBar.Maximum              = 100;
                pgBar.Minimum              = 0;
                pgBar.Value                = 0;
                btndescargarcorreo.Enabled = true;
                btnCancel.Enabled          = false;


                //mostrar_mensajes(eTipoMail.Buzon_Ent, dtp_desde.Value, dtp_hasta.Value, dir_correo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
            }
        }
Пример #3
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            string server, user, password;

            server   = textServer.Text.Trim();
            user     = textUser.Text.Trim();
            password = textPassword.Text.Trim();

            if (server.Length == 0 || user.Length == 0 || password.Length == 0)
            {
                MessageBox.Show("Please input server, user and password.");
                return;
            }

            btnStart.Enabled  = false;
            btnCancel.Enabled = true;

            ServerAuthType authType = ServerAuthType.AuthLogin;

            if (lstAuthType.SelectedIndex == 1)
            {
                authType = ServerAuthType.AuthCRAM5;
            }
            else if (lstAuthType.SelectedIndex == 2)
            {
                authType = ServerAuthType.AuthNTLM;
            }

            ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex;

            MailServer oServer = new MailServer(server, user, password,
                                                chkSSL.Checked, authType, protocol);

            //For evaluation usage, please use "TryIt" as the license code, otherwise the
            //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
            //"trial version expired" exception will be thrown.
            MailClient oClient = new MailClient("TryIt");

            //Catching the following events is not necessary,
            //just make the application more user friendly.
            //If you use the object in asp.net/windows service or non-gui application,
            //You need not to catch the following events.
            //To learn more detail, please refer to the code in EAGetMail EventHandler region
            oClient.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
            oClient.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
            oClient.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
            oClient.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
            oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

            bool bLeaveCopy = chkLeaveCopy.Checked;

            // UIDL is the identifier of every email on POP3/IMAP4/Exchange server, to avoid retrieve
            // the same email from server more than once, we record the email UIDL retrieved every time
            // if you delete the email from server every time and not to leave a copy of email on
            // the server, then please remove all the function about uidl.
            // UIDLManager wraps the function to write/read uidl record from a text file.
            UIDLManager oUIDLManager = new UIDLManager();

            try
            {
                // load existed uidl records to UIDLManager
                string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
                oUIDLManager.Load(uidlfile);

                string mailFolder = String.Format("{0}\\inbox", m_curpath);
                if (!Directory.Exists(mailFolder))
                {
                    Directory.CreateDirectory(mailFolder);
                }

                m_bcancel      = false;
                lblStatus.Text = "Connecting ...";
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                lblStatus.Text = String.Format("Total {0} email(s)", infos.Length);

                // remove the local uidl which is not existed on the server.
                oUIDLManager.SyncUIDL(oServer, infos);
                oUIDLManager.Update();

                int count = infos.Length;

                ArrayList arReport = new ArrayList();
                for (int i = 0; i < count; i++)
                {
                    MailInfo info = infos[i];
                    if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null)
                    {
                        // This email has been downloaded or checked before.
                        continue;
                    }

                    lblStatus.Text = String.Format("Retrieving mail header {0}/{1}...", info.Index, count);

                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);

                    Mail oMail = new Mail("TryIt");
                    oMail.Load(oClient.GetMailHeader(info));

                    if (!oMail.IsReport)
                    {
                        // Not a report, continue
                        // Add the email uidl to uidl file to avoid we check it next time.
                        oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                        continue;
                    }

                    // This is a report, get the entire email.
                    oMail = oClient.GetMail(info);
                    oMail.SaveAs(fileName, true);

                    ListViewItem item = new ListViewItem(oMail.From.ToString());
                    item.SubItems.Add(oMail.Subject);
                    item.SubItems.Add(oMail.ReceivedDate.ToString("yyyy-MM-dd HH:mm:ss"));
                    item.Font = new System.Drawing.Font(item.Font, FontStyle.Bold);
                    item.Tag  = fileName;
                    lstMail.Items.Insert(0, item);
                    oMail.Clear();

                    lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count);

                    arReport.Add(info); // Add the report mail info to arraylist,
                    // then we can delete it later.
                    if (bLeaveCopy)
                    {
                        // Add the email uidl to uidl file to avoid we retrieve it next time.
                        oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                    }
                }

                if (!bLeaveCopy)
                {
                    lblStatus.Text = "Deleting ...";
                    count          = arReport.Count;
                    for (int i = 0; i < count; i++)
                    {
                        MailInfo info = arReport[i] as MailInfo;
                        oClient.Delete(info);
                        // Remove UIDL from local uidl file.
                        oUIDLManager.RemoveUIDL(oServer, info.UIDL);
                    }
                }
                // Delete method just mark the email as deleted,
                // Quit method pure the emails from server exactly.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                MessageBox.Show(ep.Message);
            }

            // Update the uidl list to local uidl file and then we can load it next time.
            oUIDLManager.Update();

            lblStatus.Text    = "Completed";
            pgBar.Maximum     = 100;
            pgBar.Minimum     = 0;
            pgBar.Value       = 0;
            btnStart.Enabled  = true;
            btnCancel.Enabled = false;
        }
Пример #4
0
        private Boolean Login_server_correo_()
        {
            try
            {
                if (InfoCuenta.ServidorCorreoEntrante.Length == 0 || InfoCuenta.Usuario.Length == 0 || InfoCuenta.Password.Length == 0)
                {
                    //MessageBox.Show("Por favor ingrese servidor, usuario y contraseña.");
                }

                //oSmtpServer.User = InfoCuenta.Usuario;
                //oSmtpServer.Password = InfoCuenta.Password;
                ServerAuthType authType = ServerAuthType.AuthLogin;

                if (InfoCuenta.Tipo_Authenticacion == "APOP")
                {
                    authType = ServerAuthType.AuthCRAM5;
                }
                else if (InfoCuenta.Tipo_Authenticacion == "NTLM")
                {
                    authType = ServerAuthType.AuthNTLM;
                }


                EAGetMail.ServerProtocol protocol = new EAGetMail.ServerProtocol();


                if (InfoCuenta.TipoCuenta == "POP3")
                {
                    protocol = EAGetMail.ServerProtocol.Pop3;
                }
                if (InfoCuenta.TipoCuenta == "IMAP4")
                {
                    protocol = EAGetMail.ServerProtocol.Imap4;
                }
                if (InfoCuenta.TipoCuenta == "EXCHA_WEB_SER")
                {
                    protocol = EAGetMail.ServerProtocol.ExchangeEWS;
                }
                if (InfoCuenta.TipoCuenta == "EXCHA_WEB_DAV")
                {
                    protocol = EAGetMail.ServerProtocol.ExchangeWebDAV;
                }

                //MailServer oServer = new MailServer(server, user, password,
                //    chkSSL.Checked, authType, protocol );
                Boolean UsaSll = false;

                UsaSll = (InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo == null) ? false :(Boolean)InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo;


                MailServer oServer = new MailServer(InfoCuenta.ServidorCorreoEntrante, InfoCuenta.Usuario, InfoCuenta.Password,
                                                    UsaSll, authType, protocol);



                // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el
                // será lanzado  excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego
                // "versión de prueba expiró" se lanzará una excepción.

                MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F");

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EAGetMail EventHandler region

                oClient.OnAuthorized += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                oClient.OnConnected  += new MailClient.OnConnectedEventHandler(OnConnected);
                //oClient.OnIdle += new MailClient.OnIdleEventHandler(OnIdle);
                //oClient.OnSecuring += new MailClient.OnSecuringEventHandler(OnSecuring);
                //oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                //   bool bLeaveCopy = chkLeaveCopy.Checked;

                bool bLeaveCopy = (InfoCuenta.Guardar_1_copia_de_corre_en_server_mail == null) ? false : (Boolean)InfoCuenta.Guardar_1_copia_de_corre_en_server_mail;


                // UIDL es el identificador de cada correo electrónico de POP3 / IMAP4 / servidor de Exchange, para evitar recuperar
                // El mismo correo electrónico desde el servidor más de una vez, que registra el email UIDL recuperada cada vez
                // Si elimina el correo electrónico desde el servidor cada vez y no dejar una copia del correo electrónico en
                // El servidor, por favor, elimine toda la función sobre uidl.
                // UIDLManager envuelve la función de escribir / leer el registro uidl desde un archivo de texto.

                UIDLManager oUIDLManager = new UIDLManager();
                string      mensaje      = "";

                try
                {
                    mensaje = "Conectando al server de correo ok ...";
                    oClient.Connect(oServer);

                    MailInfo[] infos = oClient.GetMailInfos();
                    mensaje = mensaje + "  " + String.Format("Total {0} email(s)", infos.Length);

                    // Salir método puro los mensajes de correo electrónico desde el servidor exactamente.
                    oClient.Quit();
                    infos = null;

                    listErrores.Add(new cl_error_Info("0", mensaje, DateTime.Now.ToString(), "A", eTipoError.INFO, eTipoRespuesta.OK));
                    gridControl_tareas_realizadas.RefreshDataSource();
                }
                catch (Exception ex)
                {
                    mensaje = "Error al conectar con el server de correo " + ex.Message;
                    listErrores.Add(new cl_error_Info("0", mensaje, DateTime.Now.ToString(), "A", eTipoError.INFO, eTipoRespuesta.ERROR));
                    gridControl_tareas_realizadas.RefreshDataSource();

                    BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                }

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                return(false);
            }
        }
Пример #5
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                string server, user, password;
                //server = textServer.Text.Trim();
                //user = textUser.Text.Trim();
                //password = textPassword.Text.Trim();

                server   = "mail.it-corp.com";
                user     = "******";
                password = "******";

                //user = "******";
                //password = "******";

                if (server.Length == 0 || user.Length == 0 || password.Length == 0)
                {
                    MessageBox.Show("Por favor ingrese servidor, usuario y contraseña.");
                    return;
                }

                btnStart.Enabled  = false;
                btnCancel.Enabled = true;

                ServerAuthType authType = ServerAuthType.AuthLogin;
                if (lstAuthType.SelectedIndex == 1)
                {
                    authType = ServerAuthType.AuthCRAM5;
                }
                else if (lstAuthType.SelectedIndex == 2)
                {
                    authType = ServerAuthType.AuthNTLM;
                }

                ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex;

                MailServer oServer = new MailServer(server, user, password,
                                                    chkSSL.Checked, authType, protocol);

                // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el
                // será lanzado  excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego
                // "versión de prueba expiró" se lanzará una excepción.

                MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F");

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EAGetMail EventHandler region

                oClient.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                oClient.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
                oClient.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
                oClient.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
                oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                bool bLeaveCopy = chkLeaveCopy.Checked;

                // UIDL es el identificador de cada correo electrónico de POP3 / IMAP4 / servidor de Exchange, para evitar recuperar
                // El mismo correo electrónico desde el servidor más de una vez, que registra el email UIDL recuperada cada vez
                // Si elimina el correo electrónico desde el servidor cada vez y no dejar una copia del correo electrónico en
                // El servidor, por favor, elimine toda la función sobre uidl.
                // UIDLManager envuelve la función de escribir / leer el registro uidl desde un archivo de texto.

                UIDLManager oUIDLManager = new UIDLManager();

                try
                {
                    // Carga existían registros UIDL a UIDLManager
                    string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
                    oUIDLManager.Load(uidlfile);

                    string mailFolder = String.Format("{0}\\inbox", m_curpath);
                    if (!Directory.Exists(mailFolder))
                    {
                        Directory.CreateDirectory(mailFolder);
                    }

                    m_bcancel      = false;
                    lblStatus.Text = "Connecting ...";
                    oClient.Connect(oServer);
                    MailInfo[] infos = oClient.GetMailInfos();
                    lblStatus.Text = String.Format("Total {0} email(s)", infos.Length);

                    // Eliminar el uidl local que no se existía en el servidor.
                    oUIDLManager.SyncUIDL(oServer, infos);
                    oUIDLManager.Update();

                    int count = infos.Length;

                    if (count > 0)
                    {
                        lista_Mensaje = new List <mail_Mensaje_Info>();
                    }

                    for (int i = 0; i < count; i++)
                    {
                        MailInfo info = infos[i];

                        //verificar en base
                        if (Bus_Mensaje.Verifica_codMensajeId(info.UIDL) == false)
                        {
                            //}
                            //if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null /*&& "si esta en base"|| oUIDLManager.FindUIDL(oServer, info.UIDL) == null && "si esta en base"*/ )
                            //{
                            //    // este correo electrónico se ha descargado antes.
                            //    continue;
                            //}

                            lblStatus.Text = String.Format("Retrieving {0}/{1}...", info.Index, count);

                            Mail            oMail = oClient.GetMail(info);
                            System.DateTime d     = System.DateTime.Now;
                            System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                            string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                            string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i);
                            oMail.SaveAs(fileName, true);

                            //llenar grid

                            //int conta = oMail.Headers.Count;
                            //string MessageID = "";
                            //for (int y = 0; y < conta; y++)
                            //{

                            //        string valida = "Message-ID";
                            //        string extrae = oMail.Headers[y].ToString().Substring(0, 10);

                            //        string result = "";
                            //        if (extrae == valida)
                            //        {
                            //            MessageID = oMail.Headers[y].ToString();
                            //            break;
                            //        }

                            //       // break;
                            //}

                            conta = 0;
                            conta = oMail.To.ToList().Count();
                            sec   = 0;
                            foreach (var itemTo in oMail.To.ToList())
                            {
                                sec = sec + 1;
                                if (sec != conta)
                                {
                                    para += itemTo.Address + "; ";
                                }
                                else
                                {
                                    para += itemTo.Address;
                                }
                            }

                            conta = 0;
                            conta = oMail.Cc.ToList().Count();
                            sec   = 0;
                            foreach (var itemCopia in oMail.Cc.ToList())
                            {
                                sec = sec + 1;
                                if (sec != conta)
                                {
                                    CC += itemCopia.Address + "; ";
                                }
                                else
                                {
                                    CC += itemCopia.Address;
                                }
                            }

                            infoMensaje        = new mail_Mensaje_Info();
                            infoMensaje.Asunto = oMail.Subject;
                            infoMensaje.Asunto_texto_mostrado = oMail.Subject;
                            // infoMensaje.codMensajeId = MessageID;
                            infoMensaje.codMensajeId = info.UIDL;

                            infoMensaje.fileName      = fileName;
                            infoMensaje.Para          = para;
                            infoMensaje.Para_CC       = CC;
                            infoMensaje.Fecha         = oMail.ReceivedDate;
                            infoMensaje.Texto_mensaje = oMail.TextBody;

                            infoMensaje.Tiene_Adjunto = oMail.Attachments.Count() == 0 ? false : true;

                            if (Convert.ToString(oMail.Priority) == "Normal")
                            {
                                infoMensaje.Prioridad = 0;
                            }
                            if (Convert.ToString(oMail.Priority) == "Alta")
                            {
                                infoMensaje.Prioridad = 1;
                            }
                            if (Convert.ToString(oMail.Priority) == "Baja")
                            {
                                infoMensaje.Prioridad = -1;
                            }

                            infoMensaje.Leido      = false;
                            infoMensaje.Respondido = false;
                            infoMensaje.No_Leido   = false;

                            infoMensaje.mail_remitente = correo;
                            infoMensaje.Eliminado      = false;
                            infoMensaje.IdTipo_Mensaje = eTipoMail.Buzon_Ent;


                            infoMensaje.IdCuenta = IdCuenta;

                            foreach (var itemAdju in oMail.Attachments)
                            {
                                mail_Mensaje_Archi_Adjunto_Info infoAdju = new mail_Mensaje_Archi_Adjunto_Info();

                                string nomAdju = itemAdju.Name;

                                string extAdj = Path.GetExtension(nomAdju);
                                if (extAdj == ".pdf" || extAdj == ".xml")
                                {
                                    infoAdju.extensionArchivo  = extAdj;
                                    infoAdju.Archivo_adjunto   = itemAdju.Content;
                                    infoAdju.descripcion_archi = itemAdju.Name;

                                    infoMensaje.list_Archivos_Adjuntos.Add(infoAdju);
                                }
                            }

                            infoMensaje.Archivo_correo = System.IO.File.ReadAllBytes(infoMensaje.fileName);

                            lista_Mensaje.Add(infoMensaje);


                            gridControl_Correo.DataSource = lista_Mensaje;

                            gridControl_Correo.RefreshDataSource();

                            oMail.Clear();

                            // si lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count);

                            if (bLeaveCopy)
                            {
                                // añadir el uidl correo electrónico a uidl archivo para evitar recuperamos la próxima vez.
                                oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
                            }
                        }
                    }

                    if (!bLeaveCopy)
                    {
                        lblStatus.Text = "Deleting ...";
                        for (int i = 0; i < count; i++)
                        {
                            oClient.Delete(infos[i]);
                            // Eliminar UIDL de archivo uidl local.
                            oUIDLManager.RemoveUIDL(oServer, infos[i].UIDL);
                        }
                    }
                    // Eliminar método sólo marcar el correo electrónico como eliminado,
                    // Salir método puro los mensajes de correo electrónico desde el servidor exactamente.
                    oClient.Quit();

                    if (lista_Mensaje.Count() == 0)
                    {
                        MessageBox.Show("No existen Correos de Entrada Nuevos");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                    MessageBox.Show(ex.Message.ToString());
                }

                // Actualizar la lista uidl de archivo uidl local y luego podemos cargar la próxima vez.
                oUIDLManager.Update();

                lblStatus.Text    = "Completed";
                pgBar.Maximum     = 100;
                pgBar.Minimum     = 0;
                pgBar.Value       = 0;
                btnStart.Enabled  = true;
                btnCancel.Enabled = false;
            }
            catch (Exception ex)
            {
                BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString());
                MessageBox.Show(ex.Message.ToString());
            }
        }