コード例 #1
0
 private void segundoplano_DoWork(object sender, DoWorkEventArgs e)
 {
     Pop3Client emaiClient = new Pop3Client();
     try
     {
         emaiClient.Connect(servidordeemail.Text, Convert.ToInt32(porta.Value), SSL);
         emaiClient.Authenticate(usuario.Text, senha.Text);
         if (!emaiClient.Connected) return;
         var messages = new List<OpenPop.Mime.Message>();
         Total_de_Emails = emaiClient.GetMessageCount();
         for (var i = 1; i < Total_de_Emails; i++)
         {
             messages.Add(emaiClient.GetMessage(i));
             segundoplano.ReportProgress(i);
         }
         Total_de_Emails = messages.Count;
         int x = 0;
         foreach (var msg in messages.Where(y => DateTime.Parse(y.Headers.Date) >= DataInicial && DateTime.Parse(y.Headers.Date) <= DataFinal && y.FindAllAttachments() != null))
         {
             x++;
             var anexo = msg.FindAllAttachments();
             foreach (var ado in anexo.Where(c => c.FileName.EndsWith(".xml")))
             {
                 ado.Save(new FileInfo(Path.Combine(Caminho, ado.FileName)));
             }
             segundoplano.ReportProgress(x);
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message);
     }
     finally
     {
         if (emaiClient.Connected)
         {
             emaiClient.Disconnect();
             emaiClient.Dispose();
         }
     }
 }
コード例 #2
0
        public void RetrieveEmails(string EmailAddress, string Password, string ConnString, string DeleteMessage, string HostName, int Port, bool UseSsl, bool sendreceivedemail, bool SendOverDueReceivedEmail)
        {
            Pop3Client client = new Pop3Client();

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

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

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

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

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

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

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

                int parent;

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

                catch
                {
                    parent = 0;
                }

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

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

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

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

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

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

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

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

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

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

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

                        float nPercent = 0;

                        float nPercentW = 0;

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

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

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

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

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

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

                        MemoryStream m = new MemoryStream();

                        b.Save(m, ImageFormat.Jpeg);

                        Content = m.ToArray();
                    }

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

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

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

                    //AddAttachmentToDatabase(ticketid,attachment);

                }
            }

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

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

            }
        }
コード例 #3
0
        public void StartCheck()
        {
            if (Thread.CurrentThread.Name == "ThreadCheckForWrongEmails")
            {
                int waitTimeInMinutes = 2;
                if (resultContext.ListKvParams.Where(w => w.Key == "WaitCheckMailDeliveryInMinutes").Count() == 1)
                {
                    waitTimeInMinutes = Int32.Parse(resultContext.ListKvParams.Where(w => w.Key == "WaitCheckMailDeliveryInMinutes").First().Value.ToString());
                }

                Thread.Sleep((waitTimeInMinutes * 60 * 1000));
            }

            Pop3Client pop3Client = null;

            try
            {
                pop3Client = new Pop3Client();

                string mailServerPop3 = string.Empty;
                int mailServerPop3Port = 0;
                string mailFromPassword = string.Empty;
                string mailDeliverySubsystemEmail = string.Empty;

                string mailFrom = string.Empty;
                string mailTo = string.Empty;

                if (resultContext.ListKvParams.Where(w => w.Key == "DefaultEmail").Count() == 1)
                {
                    mailFrom = resultContext.ListKvParams.Where(w => w.Key == "DefaultEmail").First().Value.ToString();
                    mailTo = resultContext.ListKvParams.Where(w => w.Key == "DefaultEmail").First().Value.ToString();
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3").Count() == 1)
                {
                    mailServerPop3 = resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3").First().Value.ToString();
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3Port").Count() == 1)
                {
                    mailServerPop3Port = Int32.Parse(resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3Port").First().Value.ToString());
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailFromPassword").Count() == 1)
                {
                    mailFromPassword = resultContext.ListKvParams.Where(w => w.Key == "MailFromPassword").First().Value.ToString();
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailDeliverySubsystemEmail").Count() == 1)
                {
                    mailDeliverySubsystemEmail = resultContext.ListKvParams.Where(w => w.Key == "MailDeliverySubsystemEmail").First().Value.ToString();
                }

                List<string> listWrongEmails = new List<string>();

                DateTime dtCurrDateSent = DateTime.Now;

                pop3Client.Connect(mailServerPop3, mailServerPop3Port, true);
                pop3Client.Authenticate(mailFrom, mailFromPassword);

                Message message = null;
                int countMessages = pop3Client.GetMessageCount();
                for (int i = 1; i <= countMessages; i++)
                {
                    message = pop3Client.GetMessage(i);
                    if (message != null && message.Headers != null && message.Headers.DateSent != null &&
                        message.Headers.From.Address == mailDeliverySubsystemEmail)
                    {
                        dtCurrDateSent = message.Headers.DateSent;
                        if (message.Headers.DateSent.Kind == DateTimeKind.Utc)
                        {
                            dtCurrDateSent = message.Headers.DateSent.ToLocalTime();
                        }

                        if (this.dtStartDateSend <= dtCurrDateSent && dtCurrDateSent <= DateTime.Now)
                        {
                            if (message.MessagePart != null && message.MessagePart.GetBodyAsText().Split('\r', '\n').Where(w => w.Contains("@")).Count() > 0)
                            {
                                string wrongEmail = message.MessagePart.GetBodyAsText().Split('\r', '\n').Where(w => w.Contains("@")).First().Trim();

                                listWrongEmails.Add(wrongEmail);
                            }
                        }
                    }
                }

                List<Person> listPersonsWithWrongEmails = new List<Person>();

                ETEMDataModelEntities dbContext = new ETEMDataModelEntities();

                listPersonsWithWrongEmails = (from p in dbContext.Persons
                                              where listWrongEmails.Contains(p.EMail)
                                              orderby p.FirstName ascending, p.SecondName ascending, p.LastName ascending
                                              select p).ToList<Person>();

                if (listPersonsWithWrongEmails.Count > 0)
                {
                    string subject = (from kv in dbContext.KeyValues
                                      join kt in dbContext.KeyTypes on kv.idKeyValue equals kt.idKeyType
                                      where kt.KeyTypeIntCode == ETEMEnums.KeyTypeEnum.EmailSubject.ToString() &&
                                            kv.KeyValueIntCode == ETEMEnums.EmailSubjectEnum.WrongSentEmails.ToString()
                                      select kv.Description).FirstOrDefault();

                    string body = (from kv in dbContext.KeyValues
                                   join kt in dbContext.KeyTypes on kv.idKeyValue equals kt.idKeyType
                                   where kt.KeyTypeIntCode == ETEMEnums.KeyTypeEnum.EmailSubject.ToString() &&
                                         kv.KeyValueIntCode == ETEMEnums.EmailBodyEnum.WrongSentEmails.ToString()
                                   select kv.Description).FirstOrDefault();

                    if (!string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body))
                    {
                        string bodyInnerText = string.Empty;
                        foreach (Models.Person person in listPersonsWithWrongEmails)
                        {
                            if (string.IsNullOrEmpty(bodyInnerText))
                            {
                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_Email") + " " + person.EMail + "\n";
                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_PersonName") + " " + person.FullName;
                            }
                            else
                            {
                                bodyInnerText += "\n" + BaseHelper.GetNumberOfCharAsString('-', 100) + "\n";

                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_Email") + " " + person.EMail + "\n";
                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_PersonName") + " " + person.FullName;
                            }
                        }

                        body = string.Format(body, bodyInnerText);

                        SendMailAction(mailFrom, mailTo, subject, body);
                    }
                }
            }
            catch (Exception ex)
            {
                BaseHelper.Log("Грешка при проверка за неуспешно изпратени имейли - (ThreadCheckForWrongEmails.StartCheck)!");
                BaseHelper.Log(ex.Message);
                BaseHelper.Log(ex.StackTrace);
            }
            finally
            {
                if (pop3Client != null)
                {
                    if (pop3Client.Connected)
                    {
                        pop3Client.Disconnect();
                    }
                    pop3Client.Dispose();
                }
            }
        }