Esempio n. 1
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);
        }
Esempio n. 2
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();
            }
        }
 public string DownloadBody(object uid)
 {
     using (var pop3 = new Pop3())
     {
         ConnectAndLogin(pop3);
         IMail email = new MailBuilder().CreateFromEml(pop3.GetMessageByUID(uid.ToString()));
         return(email.Text);
     }
 }
Esempio n. 4
0
        private async Task <bool> ReadPOP3EmailBody(Email email, UserInfo userInfo)
        {
            Pop3 pop3 = await ConnectPop3(userInfo);

            var eml = await Task.Run(() => pop3.GetMessageByUID(email.Uid));

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

            email.Body = mail.Text;
            return(true);
        }
Esempio n. 5
0
        public async Task <bool> GetBody(Email email, UserInfo userInfo)
        {
            using Pop3 pop3 = await Connect(userInfo);

            var eml = await Task.Run(() => pop3.GetMessageByUID(email.Uid));

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

            email.Body = mail.Html;

            return(true);
        }
Esempio n. 6
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);
        }
Esempio n. 7
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();
            }
        }
 private void GetBody(string uid)
 {
     lock (EmailList)
     {
         var emailView = EmailList[uid.ToString()];
         if (emailView.Text == null)
         {
             lock (pop)
             {
                 MailBuilder builder = new MailBuilder();
                 IMail       email   = builder.CreateFromEml(
                     pop.GetMessageByUID(uid));
                 EmailViewManager.SetBody(ref emailView, email.Text, email.Html);
                 ListChanged = true;
             }
         }
     }
 }
Esempio n. 9
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();
            }
        }
Esempio n. 10
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;
        }
Esempio n. 11
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();
            }
        }
Esempio n. 12
0
        public Task <EmailBody> GetBodyByUID(string messageId)
        {
            var builder     = new MailBuilder();
            var message     = _pop3.GetMessageByUID(messageId);
            var email       = builder.CreateFromEml(message);
            var attachments = email?.Attachments?
                              .Select(x => new EmailAttachment()
            {
                Id = x.ContentId, Name = x.SafeFileName
            }).ToArray();

            FreeClient();

            return(Task.FromResult(new EmailBody
            {
                Text = email.Text,
                Html = email.Html,
                Attachments = attachments
            }));
        }
Esempio n. 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();
            }
        }
Esempio n. 14
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);
                    }
                }
            }
        }
Esempio n. 15
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();
            }
        }
Esempio n. 16
0
        //lấy nội dung mail
        private void dataGridView_Mail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView_Mail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
            {
                if (e.ColumnIndex == 0)
                {
                    string id = dataGridView_Mail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

                    imail = new MailBuilder().CreateFromEml(pop3.GetMessageByUID(id));
                    richTextBox_content.Text = imail.Text;

                    idmail = id;
                }
                else
                {
                    idmail = "0";
                }
            }
            else
            {
                idmail = "0";
            }
        }
Esempio n. 17
0
 private async Task <bool> ReadPop3EmailBody(Pop3 pop3, Model.Email email)
 {
     return(await Task.Run(() =>
     {
         lock (email)
         {
             if (string.IsNullOrEmpty(email.Body))
             {
                 var msg = pop3.GetMessageByUID(email.Uid);
                 MailBuilder builder = new MailBuilder();
                 IMail mail = builder.CreateFromEml(msg);
                 email.Body = mail.Text;
                 if (mail.Attachments != null)
                 {
                     // show attachment in email and when user clicks the attachment it should download
                     saveAttachmentToDisk(email.Uid, pop3);
                 }
                 return true;
             }
             return false;
         }
     }));
 }
        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();
            }
        }
Esempio n. 19
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());
            }
        }
Esempio n. 20
0
        public int GetMails(short idBox, Boolean IsProtocolBox, string boxRecipient, Func <string, string, bool> headerExistHandler, string defaultSubject)
        {
            var builder = new MailBuilder();
            var counter = 0;

            using (Pop3 mailClient = CreateMailClient())
            {
                var currentStats = mailClient.GetAccountStat();

                for (var messageCounter = (int)currentStats.MessageCount;
                     messageCounter > 0 && counter < Pars.MaxMailsForSession;
                     messageCounter--)
                {
                    if (Pars.UserCanceled())
                    {
                        return(counter);
                    }

                    var uid = mailClient.GetUID(messageCounter);

                    LogAction("Get Headers Mail Uid:" + uid);
                    byte[] headers    = mailClient.GetHeadersByUID(uid);
                    string headerHash = headers.ComputeSHA256Hash();

                    // Verifico se già presente, controlla header hash
                    var email = builder.CreateFromEml(headers);
                    LogAction(string.Format("Check Headers Mail Uid:{0} / Subject:{1} / Data:{2}", uid, email.Subject, email.Date));
                    if (headerExistHandler(headerHash, boxRecipient))
                    {
                        continue;
                    }

                    //controlla se ho già scaricata nel drop folder
                    if (MailInfo.CheckMailExist(Pars.DropFolder, headerHash))
                    {
                        continue;
                    }

                    string outpathEml, outpathXml;
                    Utils.GetDropFilenames(Pars.DropFolder, out outpathEml, out outpathXml);

                    //mail info
                    MailInfo mInfo = new MailInfo
                    {
                        Client           = MailInfo.ClientType.Pop3,
                        EmlFilename      = outpathEml,
                        IDPECMailBox     = idBox,
                        IsProtocolBox    = IsProtocolBox,
                        MailBoxRecipient = boxRecipient,
                        MailUID          = uid
                    };

                    mInfo.Parse(email);
                    mInfo.Body = "#";
                    mInfo.Size = GetMailSize(mailClient, messageCounter);
                    mInfo.SaveAs(outpathXml);

                    //download eml
                    LogAction("Download Mail Uid:" + uid);
                    byte[] eml = mailClient.GetMessageByUID(uid);
                    File.WriteAllBytes(outpathEml, eml);

                    //Aggiorna il Body
                    //Pop3 deve forzatamente scaricare l'intero messaggio per ottenere il body della mail
                    email = builder.CreateFromEml(eml);

                    mInfo.HeaderHash = headerHash;
                    mInfo.EmlHash    = eml.ComputeSHA256Hash();
                    mInfo.Body       = email.GetBodyAsHtml();
                    mInfo.UpdateStatus(MailInfo.ProcessStatus.Downloaded);
                    mInfo.Save();

                    counter++;
                }

                return(counter);
            }
        }
Esempio n. 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!");
            }
        }
Esempio n. 22
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);
            }
        }
Esempio n. 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);
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Gets specified email message from server. Use <see cref="T:Limilabs.Mail.MailBuilder" /> class to create <see cref="T:Limilabs.Mail.IMail" /> object.
 /// </summary>
 /// <exception cref="T:Limilabs.Client.POP3.Pop3ResponseException">Throws <see cref="T:Limilabs.Client.POP3.Pop3ResponseException" /> on error response.</exception>
 /// <exception cref="T:System.Exception">Invalid uid provided.</exception>
 /// <param name="uid">Unique-id of the message to get.</param>
 /// <returns>Email message.</returns>
 public byte[] GetMessageByUid(string uid)
 {
     return(_pop3.GetMessageByUID(uid));
 }
Esempio n. 25
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);
            }
        }