コード例 #1
0
ファイル: NewMail.cs プロジェクト: engrbugs/pepper.AI
        public void ReadMail(Object threadContext)
        {
            StringBuilder builder   = new StringBuilder();
            MessagePart   plaintext = _NewMessage.FindFirstPlainTextVersion();
            string        result    = "";

            if (plaintext != null)
            {
                // We found some plaintext!
                builder.Append(plaintext.GetBodyAsText());
                result = builder.ToString();
                _newMessageinPlainText = result;
            }
            else
            {
                // Might include a part holding html instead
                MessagePart html = _NewMessage.FindFirstHtmlVersion();
                if (html != null)
                {
                    // We found some html!
                    builder.Append(html.GetBodyAsText());
                    result = StripHTML(builder.ToString());
                    _newMessageinPlainText = result;
                }
            }

            int Who = FromWho(_NewMessage.Headers.From.Address);

            if (Who == -1) //cannot download attachement from UNKNOWN
            {
                ReadingOrderThruEmail(_NewMessage.Headers.From.Address, _NewMessage.Headers.Subject, result);
                _doneevent.Set();
                return;
            }

            // ### DELETED MODULE FOR PEPPER ####

            string replyMSG;

            foreach (MessagePart attachment in _NewMessage.FindAllAttachments())
            {
                //upgrade one at a time, cannot upgrade both bios and pepper in one time.
                switch (attachment.FileName)
                {
                case Variables.FilenameUpdateBios:     //BIOS Update
                    logger.Trace("Got bios Update file.");
                    File.WriteAllBytes(Variables.PathUpdateBios, attachment.Body);
                    pepThread th = new pepThread();
                    //th.UpdateBios(); <----- need to email
                    logger.Debug("Need to restart pepper.");
                    Variables.NeedtoRestart = true;

                    if (Variables.Contacts[Who].Closeness >= 75)
                    {
                        replyMSG = "Got the Bios Update " + Variables.Contacts[Who].PetName + "!!!";
                    }
                    else
                    {
                        replyMSG = "Got the Bios Update " + Variables.Contacts[Who].FirstName + "!!!";
                    }

                    //sendEmailHTML(_NewMessage.Headers.From.Address, Variables.Contacts[Who].FirstName + " " + Variables.Contacts[Who].LastName, "Re: BIOS Update", replyMSG);
                    _doneevent.Set();
                    return;

                //break;
                case Variables.FilenameUpdatePepper:     //UPDATE PEPPER "newme.pep"
                    logger.Debug("Got newme.pep PEPPER UPDATE FILE");
                    File.WriteAllBytes(Variables.PathUpdatePepper, attachment.Body);
                    logger.Debug("Need to restart pepper.");
                    Variables.NeedtoRestart = true;

                    if (Variables.Contacts[Who].Closeness >= 75)
                    {
                        replyMSG = "Got the New Dress " + Variables.Contacts[Who].PetName + "!!!";
                    }
                    else
                    {
                        replyMSG = "Got the New Dress " + Variables.Contacts[Who].FirstName + "!!!";
                    }

                    //sendEmailHTML(_NewMessage.Headers.From.Address, Variables.Contacts[Who].FirstName + " " + Variables.Contacts[Who].LastName, "Re: Pepper Upgrade", replyMSG);
                    _doneevent.Set();
                    return;
                    //break;
                }

                /* ### DELETED MODULE FOR PEPPER ####
                ### DELETED MODULE FOR PEPPER #### */
            }

            /* ### DELETED MODULE FOR PEPPER####
             ### DELETED MODULE FOR PEPPER #### */
            ReadingOrderThruEmail(_NewMessage.Headers.From.Address, _NewMessage.Headers.Subject, result);
            _doneevent.Set();
        }
コード例 #2
0
ファイル: Client.cs プロジェクト: Johannes0501/AwesomeEmail
        //List messages
        private void listMessages_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // Fetch out the selected message
            Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)];

            // If the selected node contains a MessagePart and we can display the contents - display them
            if (listMessages.SelectedNode.Tag is MessagePart)
            {
                MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag;
                if (selectedMessagePart.IsText)
                {
                    // We can show text MessageParts
                    messageTextBox.Text = selectedMessagePart.GetBodyAsText();
                }
                else
                {
                    // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...)
                    messageTextBox.Text = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>";
                }
            }
            else
            {
                // If the selected node is not a subnode and therefore does not
                // have a MessagePart in it's Tag property, we genericly find some content to show

                // Find the first text/plain version
                MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                if (plainTextPart != null)
                {
                    // The message had a text/plain version - show that one
                    messageTextBox.Text = plainTextPart.GetBodyAsText();
                }
                else
                {
                    // Try to find a body to show in some of the other text versions
                    List <MessagePart> textVersions = message.FindAllTextVersions();
                    if (textVersions.Count >= 1)
                    {
                        messageTextBox.Text = textVersions[0].GetBodyAsText();
                    }
                    else
                    {
                        messageTextBox.Text = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
                    }
                }
            }

            // Clear the attachment list from any previus shown attachments
            listAttachments.Nodes.Clear();

            // Build up the attachment list
            List <MessagePart> attachments = message.FindAllAttachments();

            foreach (MessagePart attachment in attachments)
            {
                // Add the attachment to the list of attachments
                TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName));

                // Keep a reference to the attachment in the Tag property
                addedNode.Tag = attachment;
            }

            // Only show that attachmentPanel if there is attachments in the message
            bool hadAttachments = attachments.Count > 0;

            attachmentPanel.Visible = hadAttachments;

            // Generate header table
            DataSet   dataSet = new DataSet();
            DataTable table   = dataSet.Tables.Add("Headers");

            table.Columns.Add("Header");
            table.Columns.Add("Value");

            DataRowCollection rows = table.Rows;

            // Add all known headers
            rows.Add(new object[] { "Content-Description", message.Headers.ContentDescription });
            rows.Add(new object[] { "Content-Id", message.Headers.ContentId });
            foreach (string keyword in message.Headers.Keywords)
            {
                rows.Add(new object[] { "Keyword", keyword });
            }
            foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo)
            {
                rows.Add(new object[] { "Disposition-Notification-To", dispositionNotificationTo });
            }
            foreach (Received received in message.Headers.Received)
            {
                rows.Add(new object[] { "Received", received.Raw });
            }
            rows.Add(new object[] { "Importance", message.Headers.Importance });
            rows.Add(new object[] { "Content-Transfer-Encoding", message.Headers.ContentTransferEncoding });
            foreach (RfcMailAddress cc in message.Headers.Cc)
            {
                rows.Add(new object[] { "Cc", cc });
            }
            foreach (RfcMailAddress bcc in message.Headers.Bcc)
            {
                rows.Add(new object[] { "Bcc", bcc });
            }
            foreach (RfcMailAddress to in message.Headers.To)
            {
                rows.Add(new object[] { "To", to });
            }
            rows.Add(new object[] { "From", message.Headers.From });
            rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo });
            foreach (string inReplyTo in message.Headers.InReplyTo)
            {
                rows.Add(new object[] { "In-Reply-To", inReplyTo });
            }
            foreach (string reference in message.Headers.References)
            {
                rows.Add(new object[] { "References", reference });
            }
            rows.Add(new object[] { "Sender", message.Headers.Sender });
            rows.Add(new object[] { "Content-Type", message.Headers.ContentType });
            rows.Add(new object[] { "Content-Disposition", message.Headers.ContentDisposition });
            rows.Add(new object[] { "Date", message.Headers.Date });
            rows.Add(new object[] { "Date", message.Headers.DateSent });
            rows.Add(new object[] { "Message-Id", message.Headers.MessageId });
            rows.Add(new object[] { "Mime-Version", message.Headers.MimeVersion });
            rows.Add(new object[] { "Return-Path", message.Headers.ReturnPath });
            rows.Add(new object[] { "Subject", message.Headers.Subject });

            // Add all unknown headers
            foreach (string key in message.Headers.UnknownHeaders)
            {
                string[] values = message.Headers.UnknownHeaders.GetValues(key);
                if (values != null)
                {
                    foreach (string value in values)
                    {
                        rows.Add(new object[] { key, value });
                    }
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// 接受邮件主函数
        /// </summary>
        /// <param name="name">帐号全名</param>
        /// <param name="pwd">密码</param>
        /// <param name="keyWord">关键字</param>
        /// <returns></returns>
        public string ReceiveMails(string name, string pwd, string keyWord)
        {
            string content = string.Empty;
            string server  = GetServer(name);
            Dictionary <int, Message> messages = new Dictionary <int, Message>();

            messages = new Dictionary <int, Message>();
            using (Pop3Client pop3Client = new Pop3Client())
            {
                try
                {
                    if (pop3Client.Connected)
                    {
                        pop3Client.Disconnect();
                    }
                    pop3Client.Connect(server, 110, false);
                    pop3Client.Authenticate(name, pwd);
                    int count   = pop3Client.GetMessageCount();
                    int success = 0;
                    int fail    = 0;
                    for (int i = count; i >= 1; i -= 1)
                    {
                        // Check if the form is closed while we are working. If so, abort
                        //if (IsDisposed)
                        //    return url;

                        // Refresh the form while fetching emails
                        // This will fix the "Application is not responding" problem
                        //Application.DoEvents();

                        try
                        {
                            Message message = pop3Client.GetMessage(i);

                            // Add the message to the dictionary from the messageNumber to the Message
                            messages.Add(i, message);

                            success++;

                            break;
                        }
                        catch (Exception ex)
                        {
                            this.WriteLog("读取邮件异常" + ex.ToString());
                        }
                    }

                    this.WriteLog("Mail received!\nSuccesses: " + success + "\nFailed: " + fail);

                    if (fail > 0)
                    {
                        //MessageBox.Show(this,
                        //"Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                        //"please consider sending your log file to the developer for fixing.\r\n" +
                        //"If you are able to include any extra information, please do so.",
                        //"Help improve OpenPop!");
                    }

                    // 读取最后一封邮件
                    if (messages.Count > 0)
                    {
                        // 取时间距离当前最近的一封。
                        var list = (from f in messages
                                    where f.Value.Headers.From.DisplayName == keyWord
                                    orderby f.Value.Headers.DateSent descending
                                    select f).ToList();
                        if (list.Count > 0)
                        {
                            Message message = list[0].Value;

                            // 得到的时间是东0区的时间
                            if (message.Headers.DateSent < DateTime.UtcNow.AddHours(-2))
                            {
                                // 邮件已经失效了
                                // throw new Exception("邮件已经失效了");
                            }

                            if (message.Headers.From.DisplayName == keyWord)
                            {
                                MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                                if (plainTextPart != null)
                                {
                                    // The message had a text/plain version - show that one
                                    content = plainTextPart.GetBodyAsText();
                                }
                            }
                        }
                    }
                }
                catch (InvalidLoginException)
                {
                    // 账号异常了。
                    this.WriteLog("The server did not accept the user credentials!");
                }
                catch (PopServerNotFoundException)
                {
                    this.WriteLog("The server could not be found");
                }
                catch (PopServerLockedException)
                {
                    this.WriteLog("The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?");
                }
                catch (LoginDelayException)
                {
                    this.WriteLog("Login not allowed. Server enforces delay between logins. Have you connected recently?");
                }
                catch (Exception e)
                {
                    this.WriteLog("Error occurred retrieving mail. " + e.Message);
                }
            }

            return(content);
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: Kelit/PaperEnvelope
        private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e)
        {
            // Fetch out the selected message
            Message message = messages[GetMessageNumberFromSelectedNode(treeView1.SelectedNode)];

            // If the selected node contains a MessagePart and we can display the contents - display them
            if (treeView1.SelectedNode.Tag is MessagePart)
            {
                MessagePart selectedMessagePart = (MessagePart)treeView1.SelectedNode.Tag;
                if (selectedMessagePart.IsText)
                {
                    // We can show text MessageParts
                    webBrowser1.DocumentText = selectedMessagePart.GetBodyAsText();
                    // webBrowser1.Navigating += WebBrowser1_Navigating;
                    textBox1.Text = selectedMessagePart.GetBodyAsText();
                }
                else
                {
                    // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...)
                    textBox1.Text = "<<OpenPop>>Не удается отобразить эту часть сообщения электронной почты. Это не текст<<OpenPop>>";
                }
            }
            else
            {
                // If the selected node is not a subnode and therefore does not
                // have a MessagePart in it's Tag property, we genericly find some content to show

                // Find the first text/plain version
                MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                if (plainTextPart != null)
                {
                    // The message had a text/plain version - show that one
                    textBox1.Text = plainTextPart.GetBodyAsText();
                }
                else
                {
                    // Try to find a body to show in some of the other text versions
                    List <MessagePart> textVersions = message.FindAllTextVersions();
                    if (textVersions.Count >= 1)
                    {
                        textBox1.Text = textVersions[0].GetBodyAsText();
                    }
                    else
                    {
                        textBox1.Text = "<<OpenPop>> не могу найти текстовую версию тела в это сообщение, чтобы показать <<OpenPop>>";
                    }
                }
            }

            // Clear the attachment list from any previus shown attachments
            treeView2.Nodes.Clear();

            // Build up the attachment list
            List <MessagePart> attachments = message.FindAllAttachments();

            foreach (MessagePart attachment in attachments)
            {
                // Add the attachment to the list of attachments
                TreeNode addedNode = treeView2.Nodes.Add((attachment.FileName));

                // Keep a reference to the attachment in the Tag property
                addedNode.Tag = attachment;
            }

            // Only show that attachmentPanel if there is attachments in the message
            bool hadAttachments = attachments.Count > 0;
            //attachmentPanel.Visible = hadAttachments;
        }
コード例 #5
0
        private static MailMessage CreateReply(Message source)
        {
            MailMessage reply = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["Login"], "Sender"), source.Headers.From.MailAddress);

            try
            {
                // Get message id and add 'In-Reply-To' header
                string id = source.Headers.MessageId;
                reply.Headers.Add("In-Reply-To", id);

                // Try to get 'References' header from the source and add it to the reply
                string references = source.Headers.References.ToString();

                if (!string.IsNullOrEmpty(references))
                {
                    references += ' ';
                }

                reply.Headers.Add("References", references + id);

                // Add subject
                if (!source.Headers.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase))
                {
                    reply.Subject = "Re: ";
                }

                reply.Subject += source.Headers.Subject;

                // Add body
                StringBuilder body     = new StringBuilder();
                string        passcode = GeneratePasscode();
                //Insert a Message ID and Generate passcode here into the database
                FileController.InsertMessages(source.Headers.MessageId, passcode);

                body.Append("<p>Thank you for your email!</p>");
                body.Append("<p>Here is your passcode <b>" + passcode + "</b> for accessing the attachements,please note it down to access the email in future.</p>");
                body.Append("<p>Best regards,<br>");
                body.Append("Rajesh Kumar");
                body.Append("</p>");
                body.Append("<br>");

                body.Append("<div>");
                body.AppendFormat("On {0}, ", DateTime.Today.Date.ToShortDateString());
                if (!string.IsNullOrEmpty(source.Headers.From.DisplayName))
                {
                    body.Append(source.Headers.From.DisplayName + ' ');
                }

                body.AppendFormat("<<a href=\"mailto:{0}\">{0}</a>> wrote:<br/>", source.Headers.From.Address);
                MessagePart selectedMessagePart = (MessagePart)source.MessagePart;
                if (selectedMessagePart.Body != null)
                {
                    body.Append("<blockqoute style=\"margin: 0 0 0 5px;border-left:2px blue solid;padding-left:5px\">");
                    body.Append(selectedMessagePart.GetBodyAsText());
                    body.Append("</blockquote>");
                }

                body.Append("</div>");

                reply.Body       = body.ToString();
                reply.IsBodyHtml = true;
                return(reply);
            }
            catch (Exception ex)
            {
                return(reply);
            }
        }
コード例 #6
0
ファイル: Form1.cs プロジェクト: AlexLenaerts/MailApplication
        //Lire les msg envoyés
        private void button4_Click(object sender, EventArgs e)
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            var         mails = new List <Mail>();
            MessagePart plainTextPart = null, HTMLTextPart = null;

            string pattern = @"[A-Za-z0-9]*[@]{1}[A-Za-z0-9]*[.\]{1}[A-Za-z]*";

            foreach (var msg in Manage.Receive())
            {
                //Check you message is not null
                if (msg != null)
                {
                    plainTextPart = msg.FindFirstPlainTextVersion();
                    //HTMLTextPart = msg.FindFirstHtmlVersion();
                    //mail.Html = (HTMLTextPart == null ? "" : HTMLTextPart.GetBodyAsText().Trim());
                    mails.Add(new Mail {
                        From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim())
                    });
                }
            }
            DisplayData(ManageDB.DBTOLIST(con), true);
            //DisplayData(LoadApp.mail, true);
        }
コード例 #7
0
        }//obtenir  les  emails envoyés  dans le serveur

        public void receiveMail(string userName, string psw, string service)
        {
            DataTable      dtmail           = new DataTable();
            SqlDataAdapter adapteremailrecu = CreerDataAdapter();

            adapteremailrecu.Fill(dtmail);

            Pop3Client receiveclient = new Pop3Client();

            if (receiveclient.Connected)
            {
                receiveclient.Disconnect();
            }
            receiveclient.Connect(service, 995, true);
            receiveclient.Authenticate(userName, psw);
            int           messageCount = receiveclient.GetMessageCount();
            List <string> ids          = receiveclient.GetMessageUids();

            for (int i = 0; i < messageCount; i++)
            {
                if (dtmail.Select("mailID='@id'".Replace("@id", ids[i])).Length < 1)
                {
                    DataRow dtr = dtmail.NewRow();
                    OpenPop.Mime.Message message   = receiveclient.GetMessage(i + 1);
                    string                sender   = message.Headers.From.DisplayName;
                    string                from     = message.Headers.From.Address;
                    string                subject  = message.Headers.Subject;
                    List <string>         keyw     = message.Headers.Keywords;
                    List <RfcMailAddress> mailCc   = message.Headers.Cc;
                    List <RfcMailAddress> mailTo   = message.Headers.To;
                    DateTime              dateSent = message.Headers.DateSent;
                    MessagePart           msgPart  = message.MessagePart;

                    string body  = "";
                    string bodys = "";
                    if (msgPart.IsText)
                    {
                        body  = msgPart.GetBodyAsText();
                        bodys = body;
                    }
                    else if (msgPart.IsMultiPart)
                    {
                        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                        MessagePart plainHtmlPart = message.FindFirstHtmlVersion();
                        if (plainTextPart != null)
                        {
                            body  = plainHtmlPart.GetBodyAsText();
                            bodys = plainTextPart.GetBodyAsText();
                        }
                        else
                        {
                            List <MessagePart> textVersions = message.FindAllTextVersions();
                            if (textVersions.Count >= 1)
                            {
                                body  = textVersions[0].GetBodyAsText();
                                bodys = body;
                            }
                        }
                    }
                    List <MessagePart> attachments        = message.FindAllAttachments();
                    string             pathAttachmentFile = "";
                    if (attachments.Count > 0)
                    {
                        string dir = System.Web.HttpContext.Current.Server.MapPath("~/attchment/");
                        if (!System.IO.Directory.Exists(dir))
                        {
                            System.IO.Directory.CreateDirectory(dir);
                        }
                        foreach (MessagePart attachment in attachments)
                        {
                            string    newFileName = attachment.FileName;
                            string    path        = dir + newFileName;
                            WebClient myWebClient = new WebClient();
                            myWebClient.Credentials = CredentialCache.DefaultCredentials;
                            try
                            {
                                Stream postStream = myWebClient.OpenWrite(path, "PUT");
                                if (postStream.CanWrite)
                                {
                                    postStream.Write(attachment.Body, 0, attachment.Body.Length);
                                }
                                else
                                {
                                }
                                postStream.Close();//关闭流
                                pathAttachmentFile = path + ";" + pathAttachmentFile;
                            }
                            catch
                            {
                                ;
                            }
                        }
                        attachments.Clear();
                    }
                    string bodySimple = "";
                    if (bodys.Length > 30)
                    {
                        bodySimple = bodys.Substring(0, 30);
                    }
                    else
                    {
                        bodySimple = bodys.Substring(0, bodys.Length);
                    }
                    string listCc = "";
                    foreach (RfcMailAddress address in mailCc)
                    {
                        listCc = listCc + address.Address.ToString() + ";";
                    }
                    string listTo = "";
                    foreach (RfcMailAddress address in mailTo)
                    {
                        listTo = listTo + address.ToString() + ";";
                    }
                    body                      = body.Replace(@"cid:", @"/attchment/");
                    dtr["mailID"]             = ids[i];
                    dtr["fk_userid"]          = 1;
                    dtr["mailsender"]         = sender;
                    dtr["mailfrom"]           = from;
                    dtr["mailto"]             = listTo;
                    dtr["mailcc"]             = listCc;
                    dtr["maildateTime"]       = dateSent.ToString("yyyy-MM-dd HH:mm");
                    dtr["mailsubject"]        = subject;
                    dtr["mailbodySimple"]     = bodySimple;
                    dtr["mailbody"]           = body;
                    dtr["pathAttachmentFile"] = pathAttachmentFile;
                    dtmail.Rows.Add(dtr);
                }
            }
            dtmail.DefaultView.Sort = "maildateTime DESC";
            adapteremailrecu.Update(dtmail);
        }//commuent on recevoir les email si quelqu'un envoie un émail
コード例 #8
0
ファイル: CoreFeature.cs プロジェクト: hnjm/Pos-3
        //focusing first on gMail account using recent: in username
        public void FetchRecentMessages(Account emailAccount, bool isFetchLast30days)
        {
            SqlConnection connection    = null;
            SqlCommand    cmd           = null;
            string        emailUsername = null;

            if (isFetchLast30days)
            {
                if (emailAccount.server.Contains("gmail.com"))
                {
                    emailUsername = "******" + emailAccount.username;
                }
                else
                {
                    emailUsername = emailAccount.username;
                }
                CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Fetching *last 30 days* message", EventLogEntryType.Information);
            }
            else
            {
                emailUsername = emailAccount.username;
                CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Fetching *new* message", EventLogEntryType.Information);
            }

            if (PosLibrary.CoreFeature.getInstance().Connect(emailAccount.name, emailAccount.server, emailAccount.port, emailAccount.use_ssl, emailUsername, emailAccount.password))
            {
                int count = PosLibrary.CoreFeature.getInstance().getPop3Client().GetMessageCount();
                for (int i = 1; i <= count; i++)
                {
                    //Regards to : http://hpop.sourceforge.net/exampleSpecificParts.php
                    OpenPop.Mime.Message message     = PosLibrary.CoreFeature.getInstance().getPop3Client().GetMessage(i);
                    MessagePart          messagePart = message.FindFirstPlainTextVersion();
                    if (messagePart == null)
                    {
                        messagePart = message.FindFirstHtmlVersion();
                    }
                    string messageBody = null;
                    if (messagePart != null)
                    {
                        messageBody = messagePart.GetBodyAsText();
                    }

                    messageBody = Regex.Replace(messageBody, "<.*?>", string.Empty);
                    //save to appropriate inbox
                    connection = CoreFeature.getInstance().getDataConnection();
                    string sql = "insert into inbox(account_name,sender,subject,body,date, sender_ip,[to]) values (@account_name,@sender,@subject,@body,@date,@sender_ip,@to)";
                    cmd = new SqlCommand(sql, connection);
                    cmd.Parameters.Add(new SqlParameter("account_name", emailAccount.name.ToString()));
                    cmd.Parameters.Add(new SqlParameter("sender", message.Headers.From.ToString()));
                    cmd.Parameters.Add(new SqlParameter("subject", message.Headers.Subject.ToString()));
                    cmd.Parameters.Add(new SqlParameter("body", messageBody.ToString()));
                    cmd.Parameters.Add(new SqlParameter("date", message.Headers.Date.ToString()));
                    cmd.Parameters.Add(new SqlParameter("sender_ip", message.Headers.Received[message.Headers.Received.Count - 1].Raw.ToString()));
                    cmd.Parameters.Add(new SqlParameter("to", message.Headers.To[message.Headers.To.Count - 1].ToString()));
                    try
                    {
                        int rowAffected = cmd.ExecuteNonQuery();
                        CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Inserting email inbox from " + message.Headers.From + ", subject=" + message.Headers.Subject + ", body=" + messageBody, EventLogEntryType.Information);
                    }
                    catch (Exception ex)
                    {
                        CoreFeature.getInstance().LogActivity(LogLevel.Debug, "[Internal Application Error] FetchRecentMessages " + ex.Message, EventLogEntryType.Information);
                    }
                    cmd.Dispose();
                    connection.Close();
                }

                // delete if there any message received from the server
                if (count > 0 && !emailAccount.server.Contains("gmail.com"))
                {
                    pop3Client.DeleteAllMessages();
                    pop3Client.Disconnect();
                }
            }
            else
            {
                CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Unable to login to your email", EventLogEntryType.Information);
            }
        }
コード例 #9
0
ファイル: Form1.cs プロジェクト: administradorsistemas/fccg
        private void btnCorreo_Click(object sender, EventArgs e)
        {
            string IdMsg_Error = "";

            try
            {
                messages.Clear();

                if (pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }
                pop3Client.Connect("mail.it-corp.com", 995, true);
                pop3Client.Authenticate("ryanza", "RYitcorp2014");
                // pop3Client.Authenticate("hayauca", "msabhaac20071976");
                int count = pop3Client.GetMessageCount();

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

                    string MessageId = pop3Client.GetMessageHeaders(i).MessageId;


                    // OpenPop.Mime.Header.MessageHeader messageHeader = pop3Client.GetMessageHeaders(i);
                    var itemIdMensaje = listaConsul.FirstOrDefault(q => q.codMensajeId == MessageId);


                    //IdMsg_Error = MessageId;
                    //if (/*IdMsg_Error == "*****@*****.**" || */IdMsg_Error == "*****@*****.**")
                    //{
                    //    IdMsg_Error = "";
                    //}

                    if (itemIdMensaje == null)
                    {
                        OpenPop.Mime.Message message = pop3Client.GetMessage(i);
                        messages.Add(i, message);


                        para = "";

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


                        conta = 0;
                        conta = message.Headers.Cc.ToList().Count();
                        sec   = 0;
                        foreach (var item in message.Headers.Cc.ToList())
                        {
                            //CC = item.Raw.ToString();
                            sec = sec + 1;
                            if (sec != conta)
                            {
                                CC += item.Address + "; ";
                            }
                            else
                            {
                                CC += item.Address;
                            }
                        }

                        selectedMessagePart = message.FindFirstPlainTextVersion();

                        if (selectedMessagePart != null)
                        {
                            if (selectedMessagePart.IsText)
                            {
                                valida = selectedMessagePart.GetBodyAsText();
                            }
                        }

                        Datasource.Add(new Correos()
                        {
                            Correo = message,

                            Detalle       = message.Headers.Subject,
                            Remitente     = message.Headers.From.DisplayName,
                            MessageId     = message.Headers.MessageId,
                            Fecha         = message.Headers.DateSent,
                            Para          = para,
                            Texto_Mensaje = valida,
                            Prioridad     = Convert.ToString(message.Headers.Importance),
                            From          = Convert.ToString(message.Headers.From),
                            CC            = CC,
                        }
                                       );


                        foreach (var item in Datasource)
                        {
                            List <MessagePart> attachment = item.Correo.FindAllAttachments();
                            //List<Adjunto> DatasourceAdjunto = new List<Adjunto>();

                            //foreach (MessagePart item2 in attachment)
                            //{
                            //    DatasourceAdjunto.Add(new Adjunto() { Nombre = item2.FileName, Adjunto_ = item2 });
                            //}

                            mail_Mensaje_Info info = new mail_Mensaje_Info();

                            info.Fecha  = item.Fecha;
                            info.Para   = item.Para;
                            info.Asunto = item.Detalle;
                            info.Asunto_texto_mostrado = item.Detalle;

                            info.Tiene_Adjunto = attachment.Count() == 0 ? false : true;

                            // info.Tiene_Adjunto = Convert.ToBoolean(0); //validar false

                            if (item.Prioridad == "Normal")
                            {
                                info.Prioridad = 0;
                            }
                            if (item.Prioridad == "Alta")
                            {
                                info.Prioridad = 1;
                            }
                            if (item.Prioridad == "Baja")
                            {
                                info.Prioridad = -1;
                            }

                            //info.Prioridad = 0; //validar
                            info.Leido          = false; //*Convert.ToBoolean(0);
                            info.Respondido     = false; //Convert.ToBoolean(0);
                            info.No_Leido       = false; //Convert.ToBoolean(0);
                            info.Texto_mensaje  = item.Texto_Mensaje;
                            info.mail_remitente = item.From;
                            info.Para_CC        = item.CC;
                            info.Eliminado      = false; //Convert.ToBoolean(0);
                            info.IdTipo_Mensaje = eTipoMail.Buzon_Ent;
                            info.codMensajeId   = item.MessageId;
                            // info.InfoContribuyente= null;
                            info.InfoContribuyente.Mail = item.From;

                            listaMail.Add(info);
                        }
                        // gridControl1.DataSource = Datasource;
                        // gridControl1.DataSource = listaMail;
                    }
                }

                gridControl_Buzon_Ent.DataSource = listaMail;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + IdMsg_Error);
            }
        }
コード例 #10
0
        public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction)
        {
            String host = testAction.GetParameterAsInputValue("host", false).Value;

            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentException(string.Format("Es muss ein POP3 Host angegeben sein."));
            }

            String strPort = testAction.GetParameterAsInputValue("port", false).Value;

            if (string.IsNullOrEmpty(strPort))
            {
                throw new ArgumentException(string.Format("Es muss ein POP3 Port angegeben sein."));
            }

            int port = int.Parse(strPort);

            String user = testAction.GetParameterAsInputValue("user", false).Value;

            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentException(string.Format("Es muss ein User angegeben werden."));
            }

            String password = testAction.GetParameterAsInputValue("password", false).Value;

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException(string.Format("Es muss ein Passwort angegeben werden."));
            }

            string expectedSubject = testAction.GetParameterAsInputValue("expectedSubject", false).Value;
            string expectedBody    = testAction.GetParameterAsInputValue("expectedBody", false).Value;

            pop3Client  = new Pop3Client();
            messages    = new Dictionary <int, Message>();
            logMessages = "";
            int success = 0;

            string body    = "";
            string subject = "";

            try
            {
                if (pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }
                pop3Client.Connect(host, port, false);
                pop3Client.Authenticate(user, password);
                int count = pop3Client.GetMessageCount();

                if (count > 1)
                {
                    return(new  NotFoundFailedActionResult("Command failed: There is more than one email for this user. Clear mailbox before testing!"));
                }

                if (count == 0)
                {
                    return(new  NotFoundFailedActionResult("Command failed: There is no email waiting for this user!"));
                }

                messages.Clear();
                int fail = 0;
                for (int i = count; i >= 1; i -= 1)
                {
                    try
                    {
                        // Application.DoEvents();
                        Message       message = pop3Client.GetMessage(i);
                        MessageHeader headers = pop3Client.GetMessageHeaders(i);
                        subject = headers.Subject;

                        logMessages = logMessages + "- " + i + " -" + subject + "\n";

                        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                        if (plainTextPart != null)
                        {
                            // The message had a text/plain version - show that one
                            body = plainTextPart.GetBodyAsText();
                        }
                        else
                        {
                            // Try to find a body to show in some of the other text versions
                            List <MessagePart> textVersions = message.FindAllTextVersions();
                            if (textVersions.Count >= 1)
                            {
                                body = textVersions[0].GetBodyAsText();
                            }
                            else
                            {
                                body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
                            }
                        }
                        // Build up the attachment list
                        List <MessagePart> attachments = message.FindAllAttachments();
                        foreach (MessagePart attachment in attachments)
                        {
                        }

                        // Add the message to the dictionary from the messageNumber to the Message
                        messages.Add(i, message);


                        success++;
                    }
                    catch (Exception e)
                    {
                        fail++;
                    }
                }
            }
            catch (InvalidLoginException e)
            {
                return(new VerifyFailedActionResult("Expected user mailbox: " + user + " with password: "******"The server could not be found" + e.Message));
            }
            catch (PopServerLockedException e)
            {
                return(new UnknownFailedActionResult("The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?" + e.Message));
            }
            catch (LoginDelayException e)
            {
                return(new UnknownFailedActionResult("Login not allowed. Server enforces delay between logins. Have you connected recently?" + e.Message));
            }
            catch (Exception e)
            {
                return(new UnknownFailedActionResult("Error occurred retrieving mail: " + e.Message));
            }
            finally
            {
                pop3Client.Disconnect();
            }

            if (body.Contains(expectedBody) && (subject.Contains(expectedSubject)))
            {
                return(new VerifyPassedActionResult("Subject:" + expectedSubject + "\n\rBody:" + expectedBody, "Subject: " + subject + "\n\nBody: " + body));
            }
            else
            {
                string resultMessage = "";
                if (body.Contains(expectedBody))
                {
                    resultMessage = "Body is correct.";
                }
                else
                {
                    resultMessage = "Body is not correct.";
                }
                if (subject.Contains(expectedSubject))
                {
                    resultMessage = resultMessage + " Subject is correct.";
                }
                else
                {
                    resultMessage = resultMessage + " Subject is not correct.";
                }
                return(new VerifyFailedActionResult(resultMessage + "\n\r" + "Subject:" + expectedSubject + "\n\rBody:" + expectedBody, "\n\rSubject:\n\r" + subject + "\n\rBody:" + body));
            }
        }
コード例 #11
0
        /// <summary>Takes the message part and returns the body of the text that we care about.</summary>
        /// <param name="messagePart">The email message part.</param>
        /// <returns>The string of the comment we want to save.</returns>
        private string getTextFromMessage(Message msg, bool findHTML = false, bool searchForSeperator = false, List <string> seperators = null)
        {
            string retMessage = "";

            MessagePart part = null;

            if (findHTML)
            {
                part = msg.FindFirstHtmlVersion();
                if (part == null)
                {
                    part       = msg.FindFirstPlainTextVersion();
                    retMessage = part.GetBodyAsText().ToHTML();
                }
                else
                {
                    try
                    {
                        retMessage = part.GetBodyAsText().StripWORD().ToFixedHtml();
                    }
                    catch (Exception ex)
                    {
                        part       = msg.FindFirstPlainTextVersion();
                        retMessage = part.GetBodyAsText().ToHTML();

                        //Log bad message action..
                        _eventLog.WriteMessage("", ex, "Error retrieving HTML from message. Using plain test part instead.");
                    }
                    //Check for major missing data..
                    if (retMessage.Length < (part.GetBodyAsText().Length * .5))
                    {
                        part = msg.FindFirstPlainTextVersion();
                        if (part != null)
                        {
                            retMessage = part.GetBodyAsText().ToHTML();
                        }
                    }
                }
            }
            else
            {
                retMessage = msg.FindFirstPlainTextVersion().GetBodyAsText();
            }

            //Some logfic to try and best find the seperator.
            if (searchForSeperator)
            {
                int sepLoc = 0;

                //First loop through the strings we got from
                int idx = 0;
                while (sepLoc == 0 && idx < seperators.Count)
                {
                    sepLoc = retMessage.IndexOf(seperators[idx]);
                    idx++;
                }

                //If we did not have any matches, do a more white-text based search.
                idx = 0;
                if (sepLoc == 0)
                {
                    while (sepLoc == 0 && idx < seperatorText.Count)
                    {
                        if (seperatorText[idx].IsMatch(retMessage))
                        {
                            sepLoc = seperatorText[idx].Match(retMessage).Index;
                        }
                        idx++;
                    }
                }

                //Now, let's split on the message, if we can!
                if (sepLoc > 0)
                {
                    retMessage = retMessage.Substring(sepLoc);
                }
            }

            return(retMessage);
        }
コード例 #12
0
        public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction)
        {
            String host = testAction.GetParameterAsInputValue("host", false).Value;

            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentException(string.Format("Es muss ein POP3 Host angegeben sein."));
            }

            String strPort = testAction.GetParameterAsInputValue("port", false).Value;

            if (string.IsNullOrEmpty(strPort))
            {
                throw new ArgumentException(string.Format("Es muss ein POP3 Port angegeben sein."));
            }

            int port = int.Parse(strPort);

            String user = testAction.GetParameterAsInputValue("user", false).Value;

            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentException(string.Format("Es muss ein User angegeben werden."));
            }

            String password = testAction.GetParameterAsInputValue("password", false).Value;

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException(string.Format("Es muss ein Passwort angegeben werden."));
            }


            pop3Client  = new Pop3Client();
            messages    = new Dictionary <int, Message>();
            logMessages = "";
            int success = 0;

            try
            {
                if (pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }
                pop3Client.Connect(host, port, false);
                pop3Client.Authenticate(user, password);
                int count = pop3Client.GetMessageCount();
                messages.Clear();
                int fail = 0;
                for (int i = count; i >= 1; i -= 1)
                {
                    try
                    {
                        // Application.DoEvents();
                        string        body;
                        Message       message = pop3Client.GetMessage(i);
                        MessageHeader headers = pop3Client.GetMessageHeaders(i);
                        string        subject = headers.Subject;

                        logMessages = logMessages + "- " + i + " -" + subject + "\n";

                        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                        if (plainTextPart != null)
                        {
                            // The message had a text/plain version - show that one
                            body = plainTextPart.GetBodyAsText();
                        }
                        else
                        {
                            // Try to find a body to show in some of the other text versions
                            List <MessagePart> textVersions = message.FindAllTextVersions();
                            if (textVersions.Count >= 1)
                            {
                                body = textVersions[0].GetBodyAsText();
                            }
                            else
                            {
                                body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
                            }
                        }
                        // Build up the attachment list
                        List <MessagePart> attachments = message.FindAllAttachments();
                        foreach (MessagePart attachment in attachments)
                        {
                        }

                        // Add the message to the dictionary from the messageNumber to the Message
                        messages.Add(i, message);


                        success++;
                    }
                    catch (Exception e)
                    {
                        fail++;
                    }
                }
            }
            catch (InvalidLoginException)
            {
                //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
            }
            catch (PopServerNotFoundException)
            {
                //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
            }
            catch (PopServerLockedException)
            {
                //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
            }
            catch (LoginDelayException)
            {
                //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
            }
            catch (Exception e)
            {
                return(new PassedActionResult("Error occurred retrieving mail: " + e.Message));
            }
            finally
            {
                pop3Client.Disconnect();
            }

            return(new PassedActionResult("Mails found: " + success + "\n" + logMessages));
        }
コード例 #13
0
        public void Receive(GXPOP3Session sessionInfo, GXMailMessage gxmessage)
        {
            if (client == null)
            {
                LogError("Login Error", "Must login", MailConstants.MAIL_CantLogin);
                return;
            }

            if (lastReadMessage == count)
            {
                LogDebug("No messages to receive", "No messages to receive", MailConstants.MAIL_NoMessages);
                return;
            }
            try {
                if (count > lastReadMessage)
                {
                    Message m = null;
                    try
                    {
                        m = client.GetMessage(++lastReadMessage);
                    }
                    catch (Exception e)
                    {
                        LogError("Receive message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e);
                    }

                    if (m != null)
                    {
                        MailMessage msg;
                        try
                        {
                            msg = m.ToMailMessage();
                        }
                        catch (ArgumentException ae)
                        {
                            GXLogging.Error(log, "Receive message error " + ae.Message + " subject:" + m.Headers.Subject, ae);
                            PropertyInfo subjectProp = m.Headers.GetType().GetProperty("Subject");
                            string       subject     = m.Headers.Subject;
                            if (HasCROrLF(subject))
                            {
                                subjectProp.SetValue(m.Headers, subject.Replace('\r', ' ').Replace('\n', ' '));
                                GXLogging.Warn(log, "Replaced CR and LF in subject " + m.Headers.Subject);
                            }
                            msg = m.ToMailMessage();
                        }
                        using (msg)
                        {
                            gxmessage.From = new GXMailRecipient(msg.From.DisplayName, msg.From.Address);
                            SetRecipient(gxmessage.To, msg.To);
                            SetRecipient(gxmessage.CC, msg.CC);
                            gxmessage.Subject = msg.Subject;
                            if (msg.IsBodyHtml)
                            {
                                gxmessage.HTMLText = msg.Body;
                                MessagePart plainText = m.FindFirstPlainTextVersion();
                                if (plainText != null)
                                {
                                    gxmessage.Text += plainText.GetBodyAsText();
                                }
                            }
                            else
                            {
                                gxmessage.Text = msg.Body;
                            }
                            if (msg.ReplyToList != null && msg.ReplyToList.Count > 0)
                            {
                                SetRecipient(gxmessage.ReplyTo, msg.ReplyToList);
                            }

                            gxmessage.DateSent = m.Headers.DateSent;
                            if (gxmessage.DateSent.Kind == DateTimeKind.Utc && GeneXus.Application.GxContext.Current != null)
                            {
                                gxmessage.DateSent = DateTimeUtil.FromTimeZone(m.Headers.DateSent, "Etc/UTC", GeneXus.Application.GxContext.Current);
                            }
                            gxmessage.DateReceived = GeneXus.Mail.Internals.Pop3.MailMessage.GetMessageDate(m.Headers.Date);
                            AddHeader(gxmessage, "DispositionNotificationTo", m.Headers.DispositionNotificationTo.ToString());
                            ProcessMailAttachments(gxmessage, m.FindAllAttachments());
                        }
                    }
                }
            }catch (Exception e)
            {
                LogError("Receive message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e);
            }
        }
コード例 #14
0
        //private void DepartSent_SMS()
        //{
        //    DataTable dtDepartmentSMSSent = new DataTable();
        //    dtDepartmentSMSSent = DataAccessManager.GetSMSSent( Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"]));
        //    Session["dtDepartmentSMSSent"] = dtDepartmentSMSSent;
        //    rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"];
        //}
        //protected void rgvDepartmentSent_SortCommand(object sender, GridSortCommandEventArgs e)
        //{
        //    this.rgvDepartmentSent.MasterTableView.AllowNaturalSort = true;
        //    this.rgvDepartmentSent.MasterTableView.Rebind();
        //}

        //protected void rgvDepartmentSent_PageIndexChanged(object sender, GridPageChangedEventArgs e)
        //{
        //    try
        //    {
        //        rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"];
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //}
        #endregion
        public void fetchmail(string DeptID, int CampusID)
        {
            try
            {
                DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID);
                if (dtEmailConfig.Rows.Count > 0)
                {
                    Pop3Client pop3Client;
                    pop3Client = new Pop3Client();
                    pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"]));
                    pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword);
                    if (pop3Client.Connected)
                    {
                        int count = pop3Client.GetMessageCount();
                        int progressstepno;
                        if (count == 0)
                        {
                        }
                        else
                        {
                            progressstepno = 100 - count;
                            this.Emails    = new List <Email>();
                            for (int i = 1; i <= count; i++)
                            {
                                OpenPop.Mime.Message message = pop3Client.GetMessage(i);
                                Email email = new Email()
                                {
                                    MessageNumber = i,
                                    messageId     = message.Headers.MessageId,
                                    Subject       = message.Headers.Subject,
                                    DateSent      = message.Headers.DateSent,
                                    From          = message.Headers.From.Address
                                };
                                MessagePart body = message.FindFirstHtmlVersion();
                                if (body != null)
                                {
                                    email.Body = body.GetBodyAsText();
                                }
                                else
                                {
                                    body = message.FindFirstHtmlVersion();
                                    if (body != null)
                                    {
                                        email.Body = body.GetBodyAsText();
                                    }
                                }
                                email.IsAttached = false;
                                this.Emails.Add(email);
                                //Attachment Process
                                List <MessagePart> attachments = message.FindAllAttachments();
                                foreach (MessagePart attachment in attachments)
                                {
                                    email.IsAttached = true;
                                    string FolderName = string.Empty;
                                    FolderName = Convert.ToString(Session["CampusName"]);
                                    String path = Server.MapPath("~/InboxAttachment/" + FolderName);
                                    if (!Directory.Exists(path))
                                    {
                                        // Try to create the directory.
                                        DirectoryInfo di = Directory.CreateDirectory(path);
                                    }
                                    string ext = attachment.FileName.Split('.')[1];
                                    // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString());
                                    FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString());
                                    attachment.SaveToFile(file);
                                    Attachment att = new Attachment();
                                    att.messageId = message.Headers.MessageId;
                                    att.FileName  = attachment.FileName;
                                    attItem.Add(att);
                                }
                                //System.Threading.Thread.Sleep(500);
                            }

                            //Insert into database Inbox table
                            DataTable dtStudentNo   = new DataTable();
                            bool      IsReadAndSave = false;
                            foreach (var ReadItem in Emails)
                            {
                                string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty;
                                from   = Convert.ToString(ReadItem.From);
                                subj   = Convert.ToString(ReadItem.Subject);
                                messId = Convert.ToString(ReadItem.messageId);
                                Ebody  = Convert.ToString(ReadItem.Body);
                                if (Ebody != string.Empty && Ebody != null)
                                {
                                    Ebody = Ebody.Replace("'", " ");
                                }

                                DateTime date   = ReadItem.DateSent;
                                bool     IsAtta = ReadItem.IsAttached;
                                //Student Email

                                if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"])))
                                {
                                    dtStudentNo = DyDataAccessManager.GetStudentNo(from, from);

                                    if (dtStudentNo.Rows.Count == 0)
                                    {
                                        IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(),
                                                                                                   from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"]));
                                    }
                                    else
                                    {
                                        IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(),
                                                                                                   Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"]));
                                    }
                                }
                                //Leads Email
                                if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false)
                                {
                                    dtStudentNo = DyDataAccessManager.GetLeadsID(from, from);

                                    if (dtStudentNo.Rows.Count == 0)
                                    {
                                        IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId,
                                                                                                       dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"]));
                                    }
                                    else
                                    {
                                        IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(),
                                                                                                       Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"]));
                                    }
                                }
                                //
                            }
                            //Insert into database Attachment table
                            foreach (var attachItem in attItem)
                            {
                                bool   success;
                                string Filname = attachItem.FileName;
                                string MssID   = attachItem.messageId;
                                success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname);
                            }
                            Emails.Clear();
                            // attItem.Clear();
                            pop3Client.DeleteAllMessages();
                            //StartNotification(count);
                        }
                    }

                    pop3Client.Disconnect();
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #15
0
    private void Read_Emails()
    {
        Pop3Client pop3Client;

        if (Session["Pop3Client"] == null)
        {
            pop3Client = new Pop3Client();
            pop3Client.Connect("pop.gmail.com", 995, true);

            pop3Client.Authenticate("recent:[email protected]", "umakantmore", AuthenticationMethod.UsernameAndPassword);
            //pop3Client.Authenticate("*****@*****.**", "umakantmore@08", AuthenticationMethod.UsernameAndPassword);
            Session["Pop3Client"] = pop3Client;
        }
        else
        {
            pop3Client = (Pop3Client)Session["Pop3Client"];
        }
        int count = pop3Client.GetMessageCount();

        this.Emails = new List <Email>();
        int counter = 0;

        for (int i = count; i >= 1; i--)
        {
            Message message = pop3Client.GetMessage(i);
            Email   email   = new Email()
            {
                MessageNumber = i,
                Subject       = message.Headers.Subject,
                DateSent      = message.Headers.DateSent,
                From          = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address),
            };
            MessagePart body = message.FindFirstHtmlVersion();
            if (body != null)
            {
                email.Body = body.GetBodyAsText();
            }
            else
            {
                body = message.FindFirstPlainTextVersion();
                if (body != null)
                {
                    email.Body = body.GetBodyAsText();
                }
            }
            List <MessagePart> attachments = message.FindAllAttachments();

            foreach (MessagePart attachment in attachments)
            {
                email.Attachments.Add(new Attachment
                {
                    FileName    = attachment.FileName,
                    ContentType = attachment.ContentType.MediaType,
                    Content     = attachment.Body
                });
            }
            this.Emails.Add(email);
            counter++;
            if (counter > 8)
            {
                break;
            }
        }
        repCategory.DataSource = this.Emails;
        repCategory.DataBind();
    }
コード例 #16
0
        static void SaveMessages(Account acc, List <Message> messages)
        {
            if (Directory.Exists("Mailbox") == false)
            {
                Directory.CreateDirectory("Mailbox");
            }


            foreach (var msg in messages)
            {
                string senderMail = CreateDirectory(msg, acc.Login);

                string filePath = $"Mailbox/{acc.Login}/{senderMail}/" +
                                  msg.Headers.DateSent.Day + "_" +
                                  msg.Headers.DateSent.Month + "_" +
                                  msg.Headers.DateSent.Year + "-" +
                                  msg.Headers.DateSent.Hour + "_" +
                                  msg.Headers.DateSent.Minute + "_" +
                                  msg.Headers.DateSent.Second;



                if (File.Exists(filePath + ".txt") == true || File.Exists(filePath + ".html") || File.Exists(filePath + ".xml"))
                {
                    filePath = NormalizeCloneName(filePath);
                }

                MessagePart plainText = msg.FindFirstPlainTextVersion();
                if (plainText != null)
                {
                    plainText.Save(new FileInfo($"{filePath}.txt"));
                }

                MessagePart html = msg.FindFirstHtmlVersion();
                if (html != null)
                {
                    html.Save(new FileInfo($"{filePath}.html"));
                    continue;
                }

                MessagePart xml = msg.FindFirstMessagePartWithMediaType("text/xml");
                if (xml != null)
                {
                    string xmlString           = xml.GetBodyAsText();
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml(xmlString);
                    doc.Save($"{filePath}.xml");
                    continue;
                }

                try
                {
                    File.WriteAllText($"{filePath}.txt", Encoding.ASCII.GetString(msg.RawMessage));
                }
                catch
                {
                    Utils.WriteLog($"Cannot save message with ID {msg.Headers.MessageId}", Form1.LogControl);
                }
            }

            Utils.WriteLog($"Сохранено {messages.Count} писем", Form1.LogControl);
        }
コード例 #17
0
ファイル: Email.cs プロジェクト: tieuloitu1/NewProject
        private string GetChildBody(string fromAddress, MessagePart messagePart)
        {
            if (messagePart == null)
            {
                return(string.Empty);
            }

            string child = string.Empty;

            if (messagePart.IsMultiPart)
            {
                foreach (var message in messagePart.MessageParts)
                {
                    child += " <br/> " + GetChildBody(fromAddress, message);
                }
            }
            else
            {
                child = (messagePart.Body != null && ((messagePart.ContentType.MediaType.Contains("text/html") || messagePart.ContentType.MediaType.Contains("text/plain")) ||
                                                      (fromAddress.Contains("postmaster") && (messagePart.ContentType.MediaType.Contains("message/delivery-status") || messagePart.ContentType.MediaType.Contains("text/rfc822-headers"))))) ? messagePart.GetBodyAsText() : string.Empty;
            }
            return(child);
        }
コード例 #18
0
        public void Process()
        {
            while (true)
            {
                LogIn();
                Message message;
                try
                {
                    var        fg             = client.GetMessageUids();
                    var        count          = client.GetMessageCount();
                    List <int> indexforDelete = new List <int>();
                    if (count > 0)
                    {
                        for (int i = 1; i <= count; i++)
                        {
                            message = client.GetMessage(i);
                            MessagePart mp = message.FindFirstPlainTextVersion();
                            messagesFormClents.Add(message.Headers.MessageId, message);

                            /*
                             * Console.WriteLine(mp.GetBodyAsText());
                             * Pronaci ec na osnovu MRID_ja
                             */
                            UIUpdateModel call = TryGetConsumer(mp.GetBodyAsText());
                            if (call.Gid > 0)
                            {
                                SendMailMessageToClient(message, true);
                                lock (sync)
                                {
                                    if (DMSService.Instance.Tree.Data[call.Gid].Marker == true)
                                    {
                                        clientsCall.Add(call.Gid);
                                        DMSService.Instance.Tree.Data[call.Gid].Marker = false;
                                    }
                                }
                                if (clientsCall.Count == 3)
                                {
                                    Thread t = new Thread(new ThreadStart(TraceUpAlgorithm));
                                    t.Start();
                                }
                                Publisher publisher = new Publisher();
                                publisher.PublishCallIncident(call);
                            }
                            else
                            {
                                SendMailMessageToClient(message, false);
                            }

                            indexforDelete.Add(i);
                        }
                        foreach (int item in indexforDelete)
                        {
                            client.DeleteMessage(item);
                        }
                        client.Disconnect();
                        LogIn();
                    }
                }
                catch (Exception)
                {
                    client.Disconnect();
                    LogIn();
                }
                //Console.WriteLine(message.Headers.Subject);
                Thread.Sleep(3000);
            }
        }
コード例 #19
0
        public ActionResult ReadMail()
        {
            int        eid     = Convert.ToInt32(Session["Email"]);
            var        PEmails = db.CnfiEmail.FirstOrDefault(x => x.id == eid);
            var        pid     = db.PoPP.FirstOrDefault(x => x.Pid == PEmails.Pid);
            Pop3Client pop3Client;

            if (Session["Pop3Client"] == null)
            {
                pop3Client = new Pop3Client();
                pop3Client.Connect(pid.ServerName, pid.Port, pid.SSL);
                pop3Client.Authenticate(PEmails.Email, PEmails.password);
                Session["Pop3Client"] = pop3Client;
            }
            else
            {
                pop3Client = (Pop3Client)Session["Pop3Client"];
            }
            int count   = pop3Client.GetMessageCount();
            var Emails  = new List <POPEmail>();
            int counter = 0;

            for (int i = count; i >= 1; i--)
            {
                Message  message = pop3Client.GetMessage(i);
                POPEmail email   = new POPEmail()
                {
                    MessageNumber = i,
                    Subject       = message.Headers.Subject,
                    DateSent      = message.Headers.DateSent,
                    From          = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address),
                };
                MessagePart body = message.FindFirstHtmlVersion();
                if (body != null)
                {
                    email.Body = body.GetBodyAsText();
                }
                else
                {
                    body = message.FindFirstPlainTextVersion();
                    if (body != null)
                    {
                        email.Body = body.GetBodyAsText();
                    }
                }
                List <MessagePart> attachments = message.FindAllAttachments();

                foreach (MessagePart attachment in attachments)
                {
                    email.Attachments.Add(new Attachment
                    {
                        FileName    = attachment.FileName,
                        ContentType = attachment.ContentType.MediaType,
                        Content     = attachment.Body
                    });
                }
                Emails.Add(email);
                counter++;
                if (counter > 2)
                {
                    break;
                }
            }
            var emails = Emails;

            return(View(emails));
        }