예제 #1
0
        public Task <string[]> GetAllMessageByUID()
        {
            var emailIds = _pop3.GetAll().ToArray();

            FreeClient();

            return(Task.FromResult(emailIds));
        }
        public Task BeginDownloadInboxAsync(CancellationToken token)
        {
            return(Task.Factory.StartNew(() =>
            {
                using (var pop3 = new Pop3())
                {
                    ConnectAndLogin(pop3);
                    var allUids = pop3.GetAll();
                    var chunkUids = Common.SplitList(allUids, 5);
                    var builder = new MailBuilder();

                    foreach (var uids in chunkUids)
                    {
                        var items = new List <EmailItem>();
                        foreach (var uid in uids)
                        {
                            var bytes = pop3.GetHeadersByUID(uid);
                            IMail email = builder.CreateFromEml(bytes);
                            items.Add(ParseIMail(uid, email));
                        }
                        ItemsDownloaded?.Invoke(this, items);
                    }
                }
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default));
        }
예제 #3
0
        /// <summary>
        /// Get mail using POP3 Mail Protocol
        /// </summary>
        /// <param name="folderName">Current Folder / Name of DataTable</param>
        /// <param name="emailCount">Count of email in folder</param>
        /// <param name="increment">Current Index</param>
        /// <param name="worker">BackgroundWorker that started this thread</param>
        private void GetMailUsingPOP3(string folderName, int increment, BackgroundWorker worker)
        {
            List <string> emails = _pop3.GetAll();

            foreach (string uid in emails)
            {
                // If top 5 perfect of emails, then download.
                if (float.Parse(uid) >= 42000f)
                {
                    // Add new row to DataTable
                    DataRow emailDataRow = _emailDataTableList[increment].NewRow();

                    IMail emailData = new MailBuilder()
                                      .CreateFromEml(_pop3.GetMessageByUID(uid));
                    // This takes just as long cause it downloads entire messages either way
                    emailDataRow["GUID"]    = uid;
                    emailDataRow["Date"]    = emailData.Date.ToString();
                    emailDataRow["From"]    = emailData.From;
                    emailDataRow["Body"]    = emailData.GetBodyAsHtml();
                    emailDataRow["Subject"] = emailData.Date.ToString() + " - " + emailData.Subject;
                    emailDataRow["Viewed"]  = 0;

                    _emailDataTableList[increment].Rows.Add(emailDataRow);
                }
            }
            _emailContent.Tables.Add(_emailDataTableList[increment]); //add data table if there is none in DS yet.
            _emailContent.Tables.Remove(folderName);
        }
예제 #4
0
        private void buttonClientPop_Click(object sender, EventArgs e)
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("mail.invoicedigital.cl");       // or ConnectSSL for SSL
                pop3.UseBestLogin("*****@*****.**", "sctgermany2016");

                foreach (string uid in pop3.GetAll())
                {
                    // verifico si existe el uid en la base
                    Console.WriteLine("Message unique-id: {0};", uid);
                    string nomArchivo = string.Empty;
                    if (descargaModel.exist(uid) == "False")
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(pop3.GetMessageByUID(uid));

                        Console.WriteLine("===================================================");
                        Console.WriteLine(email.Subject);
                        Console.WriteLine(email.Text);

                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save(@"C:\AdmToSii\file\xml\proveedores\" + mime.SafeFileName);
                            nomArchivo = mime.SafeFileName;
                        }
                        Console.WriteLine("===================================================");
                        descargaModel.uid        = uid;
                        descargaModel.nomArchivo = nomArchivo;
                        descargaModel.save(descargaModel);
                    }
                }
                pop3.Close();
            }
        }
예제 #5
0
        public async Task <List <Email> > GetPop3EmailHeaders(Model.UserInfo userInfo)
        {
            Pop3 pop3 = await ConnectPop3(userInfo);

            try
            {
                if (pop3 != null)
                {
                    List <string> uids    = pop3.GetAll();
                    MailBuilder   builder = new MailBuilder();
                    foreach (string uid in uids)
                    {
                        var   headers = pop3.GetHeadersByUID(uid);
                        IMail mail    = builder.CreateFromEml(headers);

                        Email email = new Email
                        {
                            Uid     = uid,
                            Date    = mail.Date ?? DateTime.MinValue,
                            Subject = mail.Subject,
                            From    = string.Join(",", mail.From?.Select(s => s.Address)),
                        };
                        emailHeaderList.Add(email);
                    }
                }
                return(emailHeaderList);
            }
            finally
            {
                serverConnection.Add(pop3);
            }
        }
예제 #6
0
        public async IAsyncEnumerable <Email> GetHeaders(UserInfo userInfo, [EnumeratorCancellation] CancellationToken token)
        {
            Pop3 pop3 = GetAvailableConnection();

            try
            {
                if (_stackUids == null)
                {
                    var uids = await Task.Run(() => pop3.GetAll());

                    _stackUids = new Stack <string>(uids);
                }

                if (_stackUids.Count > 0)
                {
                    // If scroll is turned on, load only the qty requested by scroll
                    int qtyLoad = !_settings.QtyEmailsByScroll.HasValue ? _stackUids.Count : _settings.QtyEmailsByScroll.Value;

                    MailBuilder builder = new MailBuilder();

                    for (int i = 1; i <= qtyLoad; i++)
                    {
                        if (_stackUids.TryPop(out string uid))
                        {
                            var headers = await Task.Run(() => pop3.GetHeadersByUID(uid));

                            IMail mail = builder.CreateFromEml(headers);

                            Email email = new Email
                            {
                                Uid                 = uid,
                                Date                = mail.Date ?? DateTime.MinValue,
                                Subject             = mail.Subject,
                                ListFrom            = mail.From.Select(f => $"{f.Name} <{f.Address}>").ToList(),
                                AttachmentsQuantity = mail.Attachments.Count
                            };

                            yield return(email);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                _pop3Connections.Enqueue(pop3);
            }
        }
예제 #7
0
        void loadMail()
        {
            //lblLoadMail.Visible = true;
            //prgLoadMail.Visible = true;
            int numPacket = (pop3.GetAll()).Count;

            prgLoadMail.Maximum = numPacket;
            prgLoadMail.Value   = 0;

            dtmail = new DataTable();
            dtmail.Columns.Add("id", typeof(string));
            dtmail.Columns.Add("người Gửi", typeof(string));
            dtmail.Columns.Add("chủ đề", typeof(string));
            dtmail.Columns.Add("thời gian", typeof(string));
            //int i = 1;
            foreach (string uid in pop3.GetAll())
            {
                imail = new MailBuilder().CreateFromEml(pop3.GetHeadersByUID(uid));
                DataRow row = dtmail.NewRow();
                row["id"]        = uid;
                row["người Gửi"] = imail.From.ToString();
                row["chủ đề"]    = imail.Subject;
                row["thời gian"] = imail.Date.ToString();

                if (prgLoadMail.Value >= prgLoadMail.Maximum)
                {
                    prgLoadMail.Value = prgLoadMail.Minimum;
                }
                prgLoadMail.PerformStep();
                this.Invoke((MethodInvoker) delegate() { lblLoadMail.Text = "Đã nhận " + prgLoadMail.Value + "/" + prgLoadMail.Maximum; });
                //lblLoadMail.Text = "Đã nhận " + prgLoadMail.Value + "/" + prgLoadMail.Maximum;

                dtmail.Rows.Add(row);
                dtmail.AcceptChanges();
            }

            dataGridView_Mail.DataSource = dtmail;
        }
예제 #8
0
        private IEnumerable <MailModel> GetMessagesPop3(Pop3 pop3)
        {
            var builder = new MailBuilder();
            var uids    = pop3.GetAll();

            foreach (var email in uids.Select(pop3.GetMessageByUID).Select(x => builder.CreateFromEml(x)))
            {
                yield return(new MailModel
                {
                    From = email.From.FormatFromField(),
                    To = string.Join(";", email.To),
                    Date = email.Date?.ToString("G"),
                    Subject = email.Subject,
                    Body = email.Text
                });
            }
        }
예제 #9
0
        static void Main(string[] args)
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.ConnectSSL("pop.gmail.com");  // or ConnectSSL for SSL
                pop3.UseBestLogin(Email, PW);
                List <string> uids = pop3.GetAll();
                foreach (string uid in uids)
                {
                    IMail email = new MailBuilder()
                                  .CreateFromEml(pop3.GetMessageByUID(uid));
                    Console.WriteLine(email.Subject);
                }

                Console.ReadKey();
                pop3.Close();
            }
        }
예제 #10
0
        /// <summary>
        /// IMAP
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static List <IMail> GetByPop3(ServerItem item)
        {
            var mails = new List <IMail>();

            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(item.Server, item.Port);  // or ConnectSSL for SSL
                pop3.UseBestLogin(item.User, item.Password);

                List <string> uids = pop3.GetAll();
                foreach (string uid in uids)
                {
                    mails.Add(new MailBuilder()
                              .CreateFromEml(pop3.GetMessageByUID(uid)));
                }
            }
            return(mails);
        }
예제 #11
0
        private void ReadMessages_Load(object sender, EventArgs e)
        {
            UserEmailLabel.Text = LoginForm.UserNameValue + " Mail List:";
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("pop.gmail.com", 995, true);
                pop3.UseBestLogin("recent:" + LoginForm.LoginValue, LoginForm.PasswordValue);
                List <string> UidList = pop3.GetAll();

                foreach (string uid in UidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(pop3.GetMessageByUID(uid));
                    MailListBox.Items.Add(email.From);
                    MailListBox.Items.Add(email.GetBodyAsText());
                    MailListBox.Items.Add(" ");
                }
                pop3.Close();
            }
        }
예제 #12
0
        public MainWindow()
        {
            InitializeComponent();
            Mails = new List <MailDisplay>();
            string path = "localMails";

            if (File.Exists(path))
            {
                Mails.AddRange(JsonConvert.DeserializeObject <List <MailDisplay> >(File.ReadAllText(path)));
            }


            using (Pop3 pop3 = new Pop3())
            {
                pop3.ConnectSSL("pop.mail.ru", 995);  // or ConnectSSL for SSL
                pop3.UseBestLogin("*****@*****.**", "123456Aa");
                foreach (string uid in pop3.GetAll())
                {
                    if (Mails.Any(m => m.Id == uid))
                    {
                        continue;
                    }
                    byte[] eml = pop3.GetMessageByUID(uid);

                    IMail mail = new MailBuilder().CreateFromEml(eml);

                    MailDisplay mailDisplay = new MailDisplay
                    {
                        Id       = uid,
                        Sender   = mail.Sender.Name,
                        Subject  = mail.Subject,
                        Text     = mail.Text,
                        TimeSent = mail.Date
                    };

                    Mails.Add(mailDisplay);
                }
            }

            File.WriteAllText(path, JsonConvert.SerializeObject(Mails));
            mailList.ItemsSource = Mails;
        }
예제 #13
0
        static void Main()
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(_server);                      // Use overloads or ConnectSSL if you need to specify different port or SSL.
                pop3.Login(_user, _password);               // You can also use: LoginAPOP, LoginPLAIN, LoginCRAM, LoginDIGEST methods,
                                                            // or use UseBestLogin method if you want Mail.dll to choose for you.

                List <string> uidList = pop3.GetAll();      // Get unique-ids of all messages.

                foreach (string uid in uidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        pop3.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                pop3.Close();
            }
        }
예제 #14
0
파일: Program.cs 프로젝트: Slesa/Playground
        static void Main()
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(_server);                      // Use overloads or ConnectSSL if you need to specify different port or SSL.
                pop3.Login(_user, _password);               // You can also use: LoginAPOP, LoginPLAIN, LoginCRAM, LoginDIGEST methods,
                                                            // or use UseBestLogin method if you want Mail.dll to choose for you.

                List<string> uidList = pop3.GetAll();       // Get unique-ids of all messages.

                foreach (string uid in uidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        pop3.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                pop3.Close();
            }
        }
예제 #15
0
        private void saveAttachmentToDisk(string selectedmailuid, Pop3 pop3)
        {
            List <string> uids = pop3.GetAll();

            foreach (string uid in uids)
            {
                if (uid.ToString() == selectedmailuid.ToString())
                {
                    var   eml   = pop3.GetMessageByUID(uid);
                    IMail email = new MailBuilder()
                                  .CreateFromEml(eml);

                    ReadOnlyCollection <MimeData> attachments = email.ExtractAttachmentsFromInnerMessages();
                    string emailAttachmentPath = Path.Combine(Environment.CurrentDirectory, "LocalData");
                    // save all attachments to disk
                    foreach (MimeData mime in attachments)
                    {
                        mime.Save(emailAttachmentPath + mime.SafeFileName);
                    }
                }
            }
        }
예제 #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("mail.invoicedigital.cl");       // or ConnectSSL for SSL
                pop3.UseBestLogin("*****@*****.**", "sopabru2011");

                foreach (string uid in pop3.GetAll())
                {
                    IMail email = new MailBuilder()
                                  .CreateFromEml(pop3.GetMessageByUID(uid));
                    Console.WriteLine("===================================================");
                    Console.WriteLine(email.Subject);
                    Console.WriteLine(email.Text);
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(@"C:\AdmToSii\file\libroCompra\proveedores\" + mime.SafeFileName);
                    }
                    Console.WriteLine("===================================================");
                }
                pop3.Close();
            }
        }
        public void BaixarPop3()
        {
            using (Pop3 pop3 = new Pop3())
            {
                //pop3.Connect("host sem SSL");
                pop3.ConnectSSL(this.hostPop3);
                pop3.UseBestLogin(this.MeuEmaail, this.MinhaSenha);

                foreach (string uid in pop3.GetAll())
                {
                    IMail email = new MailBuilder()
                                  .CreateFromEml(pop3.GetMessageByUID(uid));

                    Console.WriteLine(email.Subject);

                    // salva anexo no disco
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(string.Concat(this.PathAnexo, mime.SafeFileName));
                    }
                }
                pop3.Close();
            }
        }
예제 #18
0
        static public string getmsgemail(string Steamlogin)
        {
            using (Pop3 pop3 = new Pop3())
            {
                if (Config.emailssl == true)
                {
                    try
                    {
                        pop3.ConnectSSL(Config.emailserver);
                    }
                    catch (Exception e)
                    {
                        errorlog(e.Message);
                        return(null);
                    }
                }
                else
                {
                    try
                    {
                        pop3.Connect(Config.emailserver);
                    }
                    catch (Exception e)
                    {
                        errorlog(e.Message);
                        return(null);
                    }
                }
                try
                {
                    pop3.UseBestLogin(Config.emaillogin, Config.emailpassword);
                }
                catch (Exception e)
                {
                    errorlog(e.Message);
                    return(null);
                }
                MailBuilder builder = new MailBuilder();
                foreach (string uid in pop3.GetAll())
                {
                    IMail email = builder.CreateFromEml(
                        pop3.GetMessageByUID(uid));
                    long unixTime   = (long)(email.Date.Value - new DateTime(1970, 1, 1)).TotalSeconds;
                    long epochTicks = new DateTime(1970, 1, 1).Ticks;
                    long unixfTime  = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond) + 10800;

                    long unixffTime = unixfTime - unixTime;
                    if (unixffTime <= 300)
                    {
                        string text1 = getBetween(email.Text, Steamlogin.ToLower() + ":", "This email was generated because");
                        if (text1 != null)
                        {
                            return(text1.Replace("\r\n", string.Empty)
                                   .Replace("\n", string.Empty)
                                   .Replace("\r", string.Empty));
                        }
                    }
                }
                errorlog("Не могу найти письмо!");
                return(null);
            }
        }
 public List <string> GetAllUids()
 {
     return(pop.GetAll());
 }
예제 #20
0
        static void Main(string[] args)
        {
            string[] arg;
            int      flag = 0;

            arg = System.Environment.GetCommandLineArgs();
            string path = @"e:\!email-mikrotik\";

            for (int i = 0; i < arg.Length; i++)
            {
                if (arg[i] == "/dir")
                {
                    if (!String.IsNullOrEmpty(arg[i + 1]))
                    {
                        path = arg[i + 1];
                    }
                }
                if (arg[i] == "-debug")
                {
                    flag = 1;
                }

                if (arg[i] == "/?")
                {
                    Console.WriteLine("");
                    Console.WriteLine("Использование: mail2dirr.exe /dir \"папка для вложений\" [-debug] ");

                    return;
                }
            }

            //string path_base = @"e:\!email-mikrotik\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (path.Substring(path.Length - 1) != @"\")
            {
                path += @"\";
            }
            using (Pop3 pop3 = new Pop3())
            {
                try
                {
                    pop3.Connect("pop.i.ua");       // or ConnectSSL for SSL
                    pop3.UseBestLogin("*****@*****.**", "dtnjxrfcbhtyb500");
                    foreach (string uid in pop3.GetAll())
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(pop3.GetMessageByUID(uid));
                        //бесплатная библиотека мусорит сабжект письма
                        string filenam;
                        filenam = @email.Text.Replace("/", "-");
                        filenam = email.Text.Replace("\r\n", "");
                        // email.Save(@"e:\1111qa");
                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save(path + mime.SafeFileName);
                        }
                    }
                    //удаляем сообщения с сервера
                    foreach (string uid in pop3.GetAll())
                    {
                        pop3.DeleteMessageByUID(uid);
                    }
                    pop3.Close();
                }
                catch (Exception e) {
                    if (flag != 0)
                    {
                        MessageBox((IntPtr)0, e.ToString(), "mail_UDProgram_message", 0);
                    }
                    //path += "ok.ok"; if (!File.Exists(path)) File.Create(path);
                }
            }
            //ставим знак окончания приема писем
            path += "ok.ok"; if (!File.Exists(path))
            {
                File.Create(path);
            }
        }
예제 #21
0
        private void ReadMailBox(Configuration config)
        {
            log.Info("Check for Mail");
            if (!string.IsNullOrEmpty(config.AppSettings.Settings["POPServer"].Value))
            {
                try
                {
                    if (config.AppSettings.Settings["MailType"].Value == "POP")
                    {
                        using (Pop3 pop3 = new Pop3())
                        {
                            pop3.ServerCertificateValidate +=
                                new ServerCertificateValidateEventHandler(Validate);


                            pop3.ConnectSSL(config.AppSettings.Settings["POPServer"].Value);
                            //pop3.STLS();
                            pop3.Login(config.AppSettings.Settings["POPMailUser"].Value, config.AppSettings.Settings["POPMailPassword"].Value);

                            foreach (string uid in pop3.GetAll())
                            {
                                string eml  = pop3.GetMessageByUID(uid);
                                IMail  mail = new MailBuilder()
                                              .CreateFromEml(eml);

                                try
                                {
                                    mail.Attachments.ForEach(att =>
                                    {
                                        processAttachment(att, config, mail.Sender.Address);
                                    });
                                    pop3.DeleteMessageByUID(uid);
                                }
                                catch (IOException ex)
                                {
                                    log.Error(ex.InnerException);
                                }
                                catch (Exception ex)
                                {
                                    log.Error(ex);
                                }
                            }
                            pop3.Close();
                        }
                    }
                    else
                    {
                        #region IMAP
                        Imap imap = new Imap();

                        //imap.User = ;

                        //imap.Password =;
                        imap.Connect(config.AppSettings.Settings["POPServer"].Value);
                        imap.Login(config.AppSettings.Settings["POPMailUser"].Value, config.AppSettings.Settings["POPMailPassword"].Value);

                        imap.SelectInbox();

                        List <long> uidList = imap.SearchFlag(Flag.Unseen);
                        log.Debug("Go to process: " + uidList.Count + "mails");

                        foreach (long uid in uidList)
                        {
                            ISimpleMailMessage imail = new SimpleMailMessageBuilder()

                                                       .CreateFromEml(imap.GetMessageByUID(uid));

                            log.Info("Email received: " + imail.From.First().Name);

                            foreach (var att in imail.Attachments)
                            {
                                try
                                {
                                    processAttachment(att, config, imail.From.First().Address);
                                }
                                catch (IOException ex)
                                {
                                    log.Error(ex.InnerException);
                                    imap.FlagMessageByUID(uid, Flag.Flagged);
                                    imap.MarkMessageSeenByUID(uid);
                                }
                                catch (Exception ex)
                                {
                                    log.Error(ex);
                                    imap.FlagMessageByUID(uid, Flag.Flagged);
                                    imap.MarkMessageSeenByUID(uid);
                                }
                            }

                            imap.MarkMessageSeenByUID(uid);
                            imap.DeleteMessageByUID(uid);
                        }

                        imap.Close(true);
                        #endregion
                    }
                    log.Info("Mail check complete");
                }
                catch (Exception ex)
                {
                    log.Error(ex.InnerException);
                }
            }
            else
            {
                log.Info("Mail check skipped!");
            }
        }
예제 #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Veuillez entrer les éléments de facturation du client :");
            string      input       = Console.ReadLine();
            HuffmanTree huffmanTree = new HuffmanTree();

            // Construire l'arbre de huffman
            huffmanTree.Build(input);

            // Encoder
            BitArray encoded = huffmanTree.Encode(input);

            //on retourne le nombre d'octets du message lu au clavier
            Console.WriteLine();
            Console.WriteLine("Votre texte est de " + input.Length + " octets");

            //on ouvre une session de connexion sur gmail à travers smtp
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("*****@*****.**"); //expéditeur
                mail.To.Add("*****@*****.**");          //recepteur
                mail.Subject = "Informations client";                 //objet

                //ic on affiche d'abord le message compréssé chez l'expéditeur
                Console.WriteLine();

                int cpt = 0; //j'initialise un compte ici pour avoir le nombre de bit à la fin de la compression
                Console.Write("Compressé: ");
                foreach (bool bit in encoded)
                {
                    Console.Write((bit ? 1 : 0) + "");
                    cpt = cpt + 1;
                }
                Console.WriteLine();
                Console.WriteLine("le texte compréssé est de " + (cpt / 8 + 1) + " octets");

                Console.WriteLine();
                Console.WriteLine("En cours d'envoi à " + mail.To + "...");

                /*foreach (bool bit in encoded)
                 * {
                 *  mail.Body = (bit ? 1 : 0) + "";
                 * }
                 * Console.WriteLine();*/

                string chaine;
                string message = "";
                foreach (bool bit in encoded)
                {
                    chaine = (bit ? 1 : 0) + "";

                    message = $"{message}{chaine}";
                }

                mail.Body = message;

                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "testisj2019");
                SmtpServer.EnableSsl   = true;

                Console.WriteLine();
                SmtpServer.Send(mail);
                Console.WriteLine("Votre mail à été envoyé avec succes!!!");//Message succes
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //cette partie du code permet de lire les mails de l'adresse passée en paramètre
            try
            {
                using (Pop3 pop3 = new Pop3())
                {
                    pop3.ConnectSSL("pop.gmail.com"); // or ConnectSSL for SSL
                    pop3.Login("*****@*****.**", "mayelle2010");
                    List <string> uids = pop3.GetAll();
                    foreach (string uid in uids)
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(pop3.GetMessageByUID(uid));

                        Console.WriteLine("");
                        Console.WriteLine(email.Date);
                        Console.WriteLine(email.From);
                        Console.WriteLine(email.Subject);
                    }
                    pop3.Close();
                }
            }
            catch (Limilabs.Client.ServerException e)
            {
                Console.WriteLine(e.ToString());
            }
        }
예제 #23
0
        protected override void Poll()
        {
            bool      emailDownloaded = false;
            Exception error           = null;

            try
            {
                PollBegin();

                using (Pop3 pop3 = new Pop3())
                {
                    switch (_sslType)
                    {
                    case SSLType.None:
                        pop3.Connect(_host, _port);
                        break;

                    case SSLType.SSL:
                        pop3.ConnectSSL(_host, _port);
                        break;

                    case SSLType.TLS:
                        pop3.Connect(_host, _port);
                        pop3.STLS();
                        break;
                    }

                    pop3.UseBestLogin(_username, _password);

                    List <string> serverUids = pop3.GetAll();

                    MessageStoreCollection localMessageStore = MessageStoreManager.LoadLocalMessageStore(_username, _host);

                    if (localMessageStore != null)
                    {
                        MessageStoreManager.RemoveMessagesNoLongerOnServer(ref localMessageStore, serverUids);

                        List <string> uidsToCheck = MessageStoreManager.GetMessagesToCheck(localMessageStore, serverUids);

                        foreach (string uid in uidsToCheck)
                        {
                            //string fileName;

                            byte[] eml   = pop3.GetMessageByUID(uid);
                            IMail  email = new MailBuilder().CreateFromEml(eml); //SpoolEmlViaDisk(pop3.GetMessageByUID(uid), out fileName);

                            MessageStoreMessage theMessage = new MessageStoreMessage(uid);

                            if (ProcessEmailAttachments(email) > 0)
                            {
                                emailDownloaded = true;

                                //Only populate the extra data for game emails
                                if (email.From.Count > 0)
                                {
                                    theMessage.From = email.From[0].Address;
                                }

                                theMessage.Subject = email.Subject;

                                if (email.Date.HasValue)
                                {
                                    theMessage.Date      = email.Date.Value.ToString();
                                    theMessage.DateTicks = email.Date.Value.Ticks.ToString();
                                }
                                //In case the email doesn't come down with a good date
                                if (string.IsNullOrEmpty(theMessage.Date))
                                {
                                    DateTime stamp = DateTime.Now;
                                    theMessage.Date      = stamp.ToString();
                                    theMessage.DateTicks = stamp.Ticks.ToString();
                                }

                                theMessage.FileName = GetAttachmentsString(email);
                            }

                            localMessageStore.Messages.Add(theMessage);

                            //ClearSpooledEml(fileName);
                        }
                    }
                    else
                    {
                        //New message store, add all currently on server
                        localMessageStore = new MessageStoreCollection(serverUids);
                    }

                    MessageStoreManager.SaveLocalMessageStore(_username, _host, localMessageStore);

                    localMessageStore.Dispose();
                    localMessageStore = null;

                    pop3.Close();
                }
            }
            catch (Exception ex)
            {
                error = ex;
                Trace.TraceError(ex.ToString());
                Trace.Flush();
            }
            finally
            {
                PollEnd(emailDownloaded, error);
            }
        }