public static void GetTraderMessages()
 {
     try
     {
         List <OpenPop.Mime.Message> messages = FetchAllTraderMessages(hostname, port, useSsl, username, password);
         for (int i = messages.Count - 1; i >= 0; i--)
         {
             OpenPop.Mime.MessagePart xml = messages[i].FindFirstPlainTextVersion();
             if (xml != null)
             {
                 string xmlString           = xml.GetBodyAsText();
                 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                 doc.LoadXml(xmlString);
                 doc.Save("test.xml");
             }
             ProcessCycleTraderEmail readXML = new ProcessCycleTraderEmail();
             readXML.ParseProspect("test.xml");
             DeleteMessage(i + 1);
         }
         Console.Write("Processing complete.");
         Console.Read();
     }
     catch (Exception)
     {
         throw;
     }
 }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            List <Message> allaEmail = FetchAllMessages("pop.gmail.com", 995, true, "*****@*****.**", "Disneyjob");

            StringBuilder builder = new StringBuilder();

            foreach (OpenPop.Mime.Message message in allaEmail)
            {
                OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
                if (plainText != null)
                {
                    // We found some plaintext!
                    builder.Append(plainText.GetBodyAsText());
                }
                else
                {
                    // Might include a part holding html instead
                    OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
                    if (html != null)
                    {
                        // We found some html!
                        builder.Append(html.GetBodyAsText());
                    }
                }
            }
//    MessageBox.Show(builder.ToString());
            Console.WriteLine(builder.ToString());
        }
Ejemplo n.º 3
0
        public static void ListEmail()
        {
            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate("recent:[email protected]", "pass");

                if (client.Connected)
                {
                    int            count       = client.GetMessageCount();
                    List <Message> allMessages = new List <Message>(count);
                    for (int i = count; i > 0; i--)
                    {
                        allMessages.Add(client.GetMessage(i));
                    }

                    foreach (Message msg in allMessages)
                    {
                        string subject = msg.Headers.Subject;
                        string date    = msg.Headers.Date;

                        OpenPop.Mime.MessagePart plainText = msg.FindFirstPlainTextVersion();
                        Console.WriteLine("Subject: " + subject);
                        Console.WriteLine("Date: " + date);
                        Console.WriteLine("Body: " + plainText.GetBodyAsText());
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public static void ReadEmail()
        {
            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate("recent:[email protected]", "pass");

                if (client.Connected)
                {
                    Console.WriteLine("Checking inbox");
                    var count = client.GetMessageCount();
                    OpenPop.Mime.Message     message   = client.GetMessage(count);
                    OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();

                    builder.Append("Subject: " + message.Headers.Subject + "\n");
                    builder.Append("Date: " + message.Headers.Date + "\n");
                    builder.Append("Body: " + plainText.GetBodyAsText());
                    Console.WriteLine(builder.ToString());

                    //verifica se existem anexos e caso sim salva-os na pasta
                    var att = message.FindAllAttachments();

                    foreach (var ado in att)
                    {
                        ado.Save(new System.IO.FileInfo(System.IO.Path.Combine(@"C:\Users\wviegas\Documents\will", ado.FileName)));
                    }
                }
            }
        }
        private void Subjectlsbx_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedItem = Subjectlsbx.SelectedIndex;

            if (!list[selectedItem].MessagePart.IsMultiPart)
            {
                msgBodytbx.Text = list[selectedItem].MessagePart.GetBodyAsText();
            }
            else
            {
                OpenPop.Mime.MessagePart plainText = list[selectedItem].FindFirstPlainTextVersion();
                msgBodytbx.Text = plainText.GetBodyAsText();
            }
        }
Ejemplo n.º 6
0
        private void lstSubjectHeaders_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedItem = lstSubjectHeaders.SelectedIndex;

            if (list[selectedItem].MessagePart.IsMultiPart)
            {
                OpenPop.Mime.MessagePart plainText = list[selectedItem].FindFirstPlainTextVersion();
                rtxtMessageBody.Text = plainText.GetBodyAsText();
            }
            else
            {
                rtxtMessageBody.Text = list[selectedItem].MessagePart.GetBodyAsText();
            }
        }
Ejemplo n.º 7
0
        internal void get()
        {
            client.Connect("pop.gmail.com", 995, true);                      // Connects to the pop3 server for gmail
            client.Authenticate("*****@*****.**", "Max1Oreo2"); // Login Credentials



            var count = client.GetMessageCount();                                     // gets the message count

            OpenPop.Mime.Message     message   = client.GetMessage(count);            // Gets the message that correlates with the count variable- in this case 0
            OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); // Gets the first messsages body
            builder.Append(plainText.GetBodyAsText());                                //Puts the email's text into a StringBuilder where it can be outputed
            Console.WriteLine(builder.ToString());                                    //Outputs the email to the console
            builder.Clear();                                                          //Clears the String Builder
            client.Disconnect();                                                      // Disconnects from the Pop3 Client
        }
        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            list = (List <OpenPop.Mime.Message>)e.Result;

            sqliteConn = new SQLiteConnection(@"Data Source = messages.db;");
            SQLiteTransaction sqlTrans;

            SQLiteCommand commandInsert = new SQLiteCommand("INSERT OR IGNORE INTO messages (id, sender, subject, body) VALUES (@id, @sender, @subject, @body)", sqliteConn);

            //SQLiteCommand commandCount = new SQLiteCommand("SELECT COUNT(*) FROM messages", sqliteConn);

            sqliteConn.Open();

            msgcounglb.Text = Convert.ToString(list.Count);

            Subjectlsbx.Items.Clear();
            //int i = Convert.ToInt32(commandCount.ExecuteScalar());
            foreach (OpenPop.Mime.Message message in list)
            {
                if (message.Headers.MessageId != null)
                {
                    commandInsert.Parameters.AddWithValue("@id", message.Headers.MessageId);
                    commandInsert.Parameters.AddWithValue("@sender", message.Headers.From.Address);
                    commandInsert.Parameters.AddWithValue("@subject", message.Headers.Subject);
                    if (!message.MessagePart.IsMultiPart)
                    {
                        commandInsert.Parameters.AddWithValue("@body", message.MessagePart.GetBodyAsText());
                    }
                    else
                    {
                        OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
                        commandInsert.Parameters.AddWithValue("@body", plainText.GetBodyAsText());
                    }
                    sqlTrans = sqliteConn.BeginTransaction();
                    int result = commandInsert.ExecuteNonQuery();
                    sqlTrans.Commit();

                    Subjectlsbx.Items.Add(message.Headers.Subject.ToString());
                }
                //i++;
            }

            commandInsert.Dispose();
            sqliteConn.Close();
        }
Ejemplo n.º 9
0
        public static List <EmailModel> Read_Emails()
        {
            Pop3Client pop3Client;

            pop3Client = new Pop3Client();
            pop3Client.Connect("pop.gmail.com", 995, true);
            pop3Client.Authenticate("recent:[email protected]", "\"caw678\"");

            int count = pop3Client.GetMessageCount();
            List <EmailModel> emailList = new List <EmailModel>();
            List <string>     errors    = new List <string>();
            int counter = 0;

            for (int i = count; i >= count - 20; i--)
            {
                try
                {
                    if (pop3Client.GetMessage(i).Headers.ContentType.CharSet != "iso-8859-1")
                    {
                        Message message = pop3Client.GetMessage(i);

                        EmailModel email = new EmailModel();

                        email.ID       = i;
                        email.Subject  = message.Headers.Subject;
                        email.DateSent = message.Headers.DateSent;

                        OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
                        if (html != null)
                        {
                            email.Content = html.GetBodyAsText();
                        }
                        counter++;
                        emailList.Add(email);
                    }
                }
                catch (Exception ex)
                {
                    errors.Add(ex.ToString());
                }
            }

            return(emailList);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Constructs a message from a byte array.<br/>
        /// <br/>
        /// The headers are always parsed, but if <paramref name="parseBody"/> is <see langword="false"/>, the body is not parsed.
        /// </summary>
        /// <param name="rawMessageContent">The byte array which is the message contents to parse</param>
        /// <param name="parseBody">
        /// <see langword="true"/> if the body should be parsed,
        /// <see langword="false"/> if only headers should be parsed out of the <paramref name="rawMessageContent"/> byte array
        /// </param>
        public Message(byte[] rawMessageContent, bool parseBody)
        {
            RawMessage = rawMessageContent;

            // Find the headers and the body parts of the byte array
            MessageHeader headersTemp;
            byte[] body;
            HeaderExtractor.ExtractHeadersAndBody(rawMessageContent, out headersTemp, out body);

            // Set the Headers property
            Headers = headersTemp;

            // Should we also parse the body?
            if (parseBody)
            {
                // Parse the body into a MessagePart
                MessagePart = new MessagePart(body, Headers);
            }
        }
Ejemplo n.º 11
0
        private void GetMessages()
        {
            messages.Clear();
            builder.Clear();

            if (registrated == false)
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate(usersEmail.Text, passwordField.Text);
                registrated = true;
            }

            for (int i = client.GetMessageCount(); i > 1; i--)
            {
                OpenPop.Mime.Message     textMessages = client.GetMessage(i);
                OpenPop.Mime.MessagePart plainText    = textMessages.FindFirstPlainTextVersion();
                builder.Append("-----------------------------------------------------------------------------------------------------------------------------\n" + plainText.GetBodyAsText());
                messages.Text = builder.ToString();
            }
        }
Ejemplo n.º 12
0
        public static void GetTraderMessages()
        {
            try
            {
                List <OpenPop.Mime.Message> messages = FetchAllTraderMessages(hostname, port, useSsl, username, password);
                for (int i = messages.Count - 1; i >= 0; i--)
                {
                    OpenPop.Mime.MessagePart xml = messages[i].FindFirstPlainTextVersion();
                    if (xml != null)
                    {
                        string xmlString           = xml.GetBodyAsText();
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        doc.LoadXml(xmlString);
                        doc.Save("c:\\openpop\\test.xml");
                        // }  removed by jim
                        // as a non xml email ending up in mailstop would trigger
                        //a duplicate send of the last message on disk.
                        ProcessCycleTraderEmail readXML = new ProcessCycleTraderEmail();
                        try
                        {
                            readXML.ParseProspect("c:\\openpop\\test.xml");
                        }
                        catch (Exception)
                        {
                        }

                        DeleteMessage(i + 1);
                    }    //added by jim
                }
                Console.Write("Processing complete.");
                System.Threading.Thread.Sleep(10000);
                // Console.Read();
                Environment.Exit(0);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 13
0
        ///////////////////////////////////////////////////////////////////////

        public static void add_attachment(string filename, MessagePart part, int bugid, int parent_postid, IIdentity identity)
        {

            Util.write_to_log("attachment:" + filename);

            string missing_attachment_msg = "";

            int max_upload_size = Convert.ToInt32(Util.get_setting("MaxUploadSize", "100000"));
            if (part.Body.Length > max_upload_size)
            {
                missing_attachment_msg = "ERROR: email attachment exceeds size limit.";
            }

            string content_type = part.ContentType.MediaType;
            string desc;
            MemoryStream attachmentStream = new MemoryStream(part.Body);

            if (missing_attachment_msg == "")
            {
                desc = "email attachment";
            }
            else
            {
                desc = missing_attachment_msg;
            }

            attachmentStream.Position = 0;
            Bug.insert_post_attachment(
                identity,
                bugid,
                attachmentStream,
                (int)attachmentStream.Length,
                filename,
                desc,
                content_type,
                parent_postid,
                false,  // not hidden
                false); // don't send notifications

        }
Ejemplo n.º 14
0
        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            list = (List <OpenPop.Mime.Message>)e.Result;
            try
            {
                SQLiteConnection  sqliteCon = new SQLiteConnection(@"Data Source = messages.db;");
                SQLiteTransaction sqlTrans;
                sqliteCon.Open();



                SQLiteCommand commandInsert = new SQLiteCommand("INSERT OR IGNORE INTO messages (msgID, msgSender, msgSubject, msgBody) VALUES ( @msgID, @msgSender, @msgSubject, @msgBody)", sqliteCon);
                // SQLiteCommand commandCount = new SQLiteCommand("SELECT COUNT(*) FROM messages", sqliteConn);

                /*
                 *
                 * string crtMessagetblSQL = "CREATE TABLE IF NOT EXISTS [Messages] (" +
                 *          "[msgID] TEXT NOT NULL PRIMARY KEY," +
                 *          "[msgSender] TEXT NULL," +
                 *          "[msgSubject] TEXT NULL," +
                 *          "[msgBody] TEXT NULL)";
                 *         // "[msgIndex] INTEGER )";
                 *
                 * using (SQLiteTransaction sqlTrans1 = sqliteCon.BeginTransaction())
                 * {
                 *  SQLiteCommand crtComm = new SQLiteCommand(crtMessagetblSQL, sqliteCon);
                 *
                 *  crtComm.ExecuteNonQuery();
                 *  crtComm.Dispose();
                 *
                 *  sqlTrans1.Commit(); // Commit changes into the DB
                 * }
                 */
                msgcounglb.Text = Convert.ToString(list.Count);

                //  Subjectlsbx.Items.Clear();
                //int i = Convert.ToInt32(commandCount.ExecuteScalar());
                foreach (OpenPop.Mime.Message message in list)
                {
                    if (message.Headers.MessageId != null)
                    {
                        commandInsert.Parameters.AddWithValue("@msgID", message.Headers.MessageId);
                        commandInsert.Parameters.AddWithValue("@msgSender", message.Headers.From.Address);
                        commandInsert.Parameters.AddWithValue("@msgSubject", message.Headers.Subject);
                        if (!message.MessagePart.IsMultiPart)
                        {
                            commandInsert.Parameters.AddWithValue("@msgBody", message.MessagePart.GetBodyAsText());
                        }
                        else
                        {
                            OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
                            commandInsert.Parameters.AddWithValue("@msgBody", plainText.GetBodyAsText());
                        }

                        // SQLiteCommand cmdFindIndex = new SQLiteCommand("SELECT MAX(msgIndex) from messages", sqliteCon);
                        // object anObj = cmdFindIndex.ExecuteScalar();

                        //int maxIndex = (anObj == null ? -1 : Convert.ToInt32(anObj.ToString()));

                        // maxIndex++;
                        // commandInsert.Parameters.AddWithValue("@msgIndex", maxIndex);

                        sqlTrans = sqliteCon.BeginTransaction();
                        // SQLiteCommand crtComm = new SQLiteCommand(crtMessagetblSQL, sqliteCon);
                        int result = commandInsert.ExecuteNonQuery();
                        sqlTrans.Commit();
                        updatDB();

                        // Subjectlsbx.Items.Add(message.Headers.Subject.ToString());
                    }
                }
            }
            catch (SQLiteException r)
            {
                MessageBox.Show(r.ToString());
            } // End catch
        }
Ejemplo n.º 15
0
        private bool ParseAndSaveDailyBudget(MessagePart attachment, DateTime sentDate, string subject, string address)
        {
            KpiBudget kpiBudget = ParseC810(attachment.Body);
            if (kpiBudget != null)
            {
                Log.n("Vedlegget '" + attachment.FileName + "' fra e-posten: \""
                    + subject + "\" fra: \"" + address + "\" sendt: " + sentDate.ToShortDateString() + " er avlest og verifisert.");
                if (SaveBudget(kpiBudget))
                {
                    Log.d("Budsjett lagret til databasen");
                    return true;
                }
            }
            countEmailAttempts++;
            if (countEmailAttempts > limitEmailAttempts)
                maxEmailAttemptsReached = true;

            Log.n("Vedlegget '" + attachment.FileName + "' fra e-posten: \""
                + subject + "\" fra: \"" + address + "\" sendt: " + sentDate.ToShortDateString() + " er ugyldig, feil eller var ikke av typen C810");
            return false;
        }
Ejemplo n.º 16
0
 private bool AttachmentMatch(MessagePart attachment)
 {
     return attachment != null
         && attachment.FileName.ToLower().Contains(matchAttachmentFilenameMustContain)
         && attachment.FileName.ToLower().EndsWith(".pdf");
 }
Ejemplo n.º 17
0
        private void fetchAllMessages(object sender, DoWorkEventArgs e)
        {
            int percentComplete;

            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                //client.Connect("pop.gmail.com", 995, true);
                //Taking the data from usersettings.settings
                client.Connect(MailClient__.Properties.Settings.Default.openpopserver, MailClient__.Properties.Settings.Default.popport, MailClient__.Properties.Settings.Default.EnableSSL);



                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                messageCount = client.GetMessageCount();

                // We want to download all messages
                List <OpenPop.Mime.Message> allMessages = new List <OpenPop.Mime.Message>(messageCount);


                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number

                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                    percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100);
                    (sender as BackgroundWorker).ReportProgress(percentComplete);
                }

                // Now return the fetched messages
                e.Result = allMessages;



                SQLiteCommand commandInsert = new SQLiteCommand("INSERT OR IGNORE INTO messages (id, sender, subject, body) VALUES (@id, @sender, @subject, @body)", connection);
                connection.Open();

                foreach (OpenPop.Mime.Message message in allMessages)
                {
                    if (message.Headers.MessageId != null)
                    {
                        commandInsert.Parameters.AddWithValue("@id", message.Headers.MessageId);
                        commandInsert.Parameters.AddWithValue("@sender", message.Headers.From.Address);
                        commandInsert.Parameters.AddWithValue("@subject", message.Headers.Subject);
                        if (!message.MessagePart.IsMultiPart)
                        {
                            commandInsert.Parameters.AddWithValue("@body", message.MessagePart.GetBodyAsText());
                        }
                        else
                        {
                            OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
                            commandInsert.Parameters.AddWithValue("@body", plainText.GetBodyAsText());
                        }

                        int result = commandInsert.ExecuteNonQuery();
                    }
                }

                commandInsert.Dispose();
                connection.Close();
            }
        }
        private void workTimer_Tick(object sender, ElapsedEventArgs e)
        {
            try
            {
                // Log.Info($"Checking for new alerts...");

                string readEmailFile = "ReadEmails.id";

                List <String> seenMessages = new List <String>();
                if (File.Exists(readEmailFile))
                {
                    seenMessages = File.ReadAllLines(readEmailFile).ToList();
                }

                List <Message> NewMessages = FetchUnseenMessages(Email_Pop_Server,
                                                                 Convert.ToInt32(Email_Pop_Port),
                                                                 Convert.ToBoolean(Email_Pop_SSL),
                                                                 Email_Pop_User,
                                                                 Email_Pop_Password,
                                                                 seenMessages);

                string threatid = "";

                for (int i = 0; i < NewMessages.Count; i++)

                {
                    Log.Info($"New email: " + NewMessages[i].Headers.Subject);

                    OpenPop.Mime.MessagePart htmlBody = NewMessages[i].FindFirstHtmlVersion();
                    EmailSubject = NewMessages[i].Headers.Subject;

                    if (htmlBody != null)
                    {
                        threatid = htmlBody.GetBodyAsText();
                    }

                    int start = threatid.IndexOf("analyze/threats/") + 16;
                    int end   = threatid.IndexOf("/overview") - threatid.IndexOf("analyze/threats/") - 16;
                    threatid = threatid.Substring(start, end);
                    // Log.Info($"{nameof(Service.S1Notifier)} Threat ID: " + threatid);

                    var JsonSettings = new Newtonsoft.Json.JsonSerializerSettings
                    {
                        NullValueHandling     = Newtonsoft.Json.NullValueHandling.Include,
                        MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
                    };
                    var    restClient     = new RestClientInterface();
                    string resourceString = ManagementServer + "/web/api/v1.6/threats/" + threatid;
                    // threatid = "59d5239e75c5fa05cf6d74d0";
                    // 59d5239e75c5fa05cf6d74d0
                    // string resourceString = ManagementServer + "/web/api/v1.6/threats/59d5239e75c5fa05cf6d74d0";
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;
                    var     batch_string = restClient.MakeRequest(Token).ToString();
                    dynamic threat       = Newtonsoft.Json.JsonConvert.DeserializeObject(batch_string, JsonSettings);
                    EmailBody = Newtonsoft.Json.Linq.JObject.Parse(batch_string.ToString()).ToString(Newtonsoft.Json.Formatting.Indented);
                    Log.Info($"Threat Details: " + EmailBody);

                    // Agent info ==============================================================================================
                    string agentid = threat.agent;
                    resourceString      = ManagementServer + "/web/api/v1.6/agents/" + agentid;
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;
                    var     agent_string = restClient.MakeRequest(Token).ToString();
                    dynamic agent        = Newtonsoft.Json.JsonConvert.DeserializeObject(agent_string, JsonSettings);

                    // Forensic info ==============================================================================================
                    resourceString      = ManagementServer + "/web/api/v1.6/threats/" + threatid + "/forensics/export/json";
                    restClient.EndPoint = resourceString;
                    restClient.Method   = HttpVerb.GET;
                    var     forensic_string = restClient.MakeRequest(Token).ToString();
                    dynamic forensic        = Newtonsoft.Json.JsonConvert.DeserializeObject(forensic_string, JsonSettings);
                    string  forensic_output = Newtonsoft.Json.Linq.JObject.Parse(forensic_string.ToString()).ToString(Newtonsoft.Json.Formatting.Indented);

                    // Get the assembly information
                    System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                    // Location is where the assembly is run from
                    string assemblyLocation = assemblyInfo.CodeBase;
                    assemblyLocation = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf('/'));
                    string report_file = assemblyLocation + "/email.html";
                    string local_path  = new Uri(report_file).LocalPath;
                    string report      = File.ReadAllText(local_path);

                    string timestamp   = threat.created_date.ToString();
                    string description = threat.description;
                    string resolved    = threat.resolved;
                    string status      = threat.mitigation_status;

                    string filename = threat.file_id.display_name;
                    string filepath = threat.file_id.path;
                    string filehash = threat.file_id.content_hash;

                    string rawdata = EmailBody;

                    switch (status)
                    {
                    case "0":
                        status = "<p class='S1Mitigated'>Mitigated</p>";
                        break;

                    case "1":
                        status = "<p class='S1Active'>Active</p>";
                        break;

                    case "2":
                        status = "<p class='S1Blocked'>Blocked</p>";
                        break;

                    case "3":
                        status = "<p class='S1Suspicious'>Suspicious</p>";
                        break;

                    case "4":
                        status = "<p class='S1Suspicious'>Pending</p>";
                        break;

                    case "5":
                        status = "<p class='S1Suspicious'>Suspicious cancelled</p>";
                        break;

                    default:
                        status = "<p class='S1Mitigated'>Mitigated</p>";
                        break;
                    }

                    switch (resolved.ToLower())
                    {
                    case "true":
                        resolved = "<p class='S1Green'>Yes</p>";
                        break;

                    case "false":
                        resolved = "<p class='S1Red'>No</p>";
                        break;

                    default:
                        resolved = "<p class='S1Red'>No</p>";
                        break;
                    }

                    string threatlink = "<a href='" + ManagementServer + "/#/analyze/threats/" + threatid + "/overview'>" + threatid + "</a>";
                    report = report.Replace("$threatid$", threatlink);
                    report = report.Replace("$timestamp$", timestamp);
                    report = report.Replace("$description$", description);
                    report = report.Replace("$resolved$", resolved);
                    report = report.Replace("$status$", status);

                    report = report.Replace("$filename$", filename);
                    report = report.Replace("$filepath$", filepath);
                    report = report.Replace("$filehash$", "<a href='https://www.virustotal.com/latest-scan/" + filehash + "'>" + filehash + "</a>");

                    string code = SyntaxHighlightJson(rawdata.Replace("\r\n", "<br/>").Replace(" ", "&nbsp;"));
                    // Log.Info($"{nameof(Service.S1Notifier)} Code: " + code);
                    report = report.Replace("$rawdata$", "<span class='Code'>" + code + "</span>");

                    string forensicdata = SyntaxHighlightJson(forensic_output.Replace("\r\n", "<br/>").Replace(" ", "&nbsp;"));
                    report = report.Replace("$forensicdata$", "<span class='Code'>" + forensicdata + "</span>");

                    string computername = agent.network_information.computer_name;
                    string os           = agent.software_information.os_name;
                    string agentversion = agent.agent_version;
                    string agentip      = agent.external_ip;
                    string machinetype  = agent.hardware_information.machine_type;

                    report = report.Replace("$computername$", computername);
                    report = report.Replace("$os$", os);
                    report = report.Replace("$agentversion$", agentversion);
                    report = report.Replace("$agentip$", agentip);
                    report = report.Replace("$machinetype$", machinetype);

                    EmailBody = report;

                    SendEmail();
                }

                File.WriteAllLines(readEmailFile, seenMessages);
            }
            catch (Exception ex)
            {
                Log.Error($"Error in mail processing: " + ex.Message);
            }
        }
Ejemplo n.º 19
0
 private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
 {
     OpenPop.Mime.Message     msg     = pop3Client.GetMessage(count - dataGridView.CurrentCell.RowIndex);
     OpenPop.Mime.MessagePart msgpart = msg.FindFirstPlainTextVersion();
     MessageBox.Show("From: " + msg.Headers.From + "\nSubject: " + msg.Headers.Subject + "\nMessage: " + msg.MessagePart.BodyEncoding.GetString(msgpart.Body), "Message", MessageBoxButtons.OK);
 }
Ejemplo n.º 20
0
        private static void CleanUpInbox()
        {
            OpenPop.Pop3.Pop3Client p3 = new OpenPop.Pop3.Pop3Client();
            int iPort = 110;

            iPort = 995;
            bool bSSL = false;

            bSSL = true;
            string sPopHost = Saved.Code.Common.GetBMSConfigurationKeyValue("outlookhost");
            string sPopUser = Saved.Code.Common.GetBMSConfigurationKeyValue("smtppopuser");
            string sPopPass = Saved.Code.Common.GetBMSConfigurationKeyValue("smtppoppassword");

            p3.Connect(sPopHost, iPort, bSSL, 7000, 7000, null);
            p3.Authenticate(sPopUser, sPopPass);
            int iCount = p3.GetMessageCount();
            int i      = 0;

            for (i = iCount; i > 0; i--)
            {
                try
                {
                    MessageHeader            h         = p3.GetMessageHeaders(i);
                    Message                  m         = p3.GetMessage(i);
                    OpenPop.Mime.MessagePart plainText = m.FindFirstPlainTextVersion();
                    OpenPop.Mime.MessagePart htmlPart  = m.FindFirstHtmlVersion();
                    string body     = "";
                    string myto     = m.Headers.Subject;
                    string mysentto = "";

                    if (myto != null)
                    {
                        string[] vTo = myto.Split(new string[] { "-" }, StringSplitOptions.None);
                        if (vTo.Length > 1)
                        {
                            mysentto = vTo[1].Trim();
                        }
                    }


                    if (plainText != null)
                    {
                        body += plainText.GetBodyAsText();
                    }
                    if (htmlPart != null)
                    {
                        body += htmlPart.GetBodyAsText();
                    }
                    bool fTotaled = false;
                    if (body.Contains("be delivered to one"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("hop count exceeded"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("A communication failure occurred"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("The email address you entered couldn't be found"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("The domain you attempted to contact"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("I'm afraid I wasn't able to deliver the following message"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("cannot be delivered"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("I was unable to deliver your message"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("Your message wasn't delivered"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("rejected your message to the following"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("Delivery to the following recipient failed permanently"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("This is a delivery failure notification message "))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("Delivery has failed to these recipients or groups"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("There was a temporary problem delivering your message "))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("The following addresses had permanent fatal errors"))
                    {
                        fTotaled = true;
                    }

                    else if (body.Contains("the receiving email server outside Office 365 reported ") || body.Contains("couldn't be delivered"))
                    {
                        fTotaled = true;
                    }

                    if (fTotaled)
                    {
                        string sql = "update Leads set Advertised=getdate() where email='" + mysentto + "'";
                        Saved.Code.Common.gData.Exec(sql);
                        p3.DeleteMessage(i);
                    }
                }
                catch (Exception)
                {
                }
            }

            p3.Disconnect();
        }
Ejemplo n.º 21
0
        private void button11_Click(object sender, EventArgs e)
        {
            dt = new DataTable("Inbox");
            dt.Columns.Add("ID");
            dt.Columns.Add("Temat");
            dt.Columns.Add("Sender");
            dt.Columns.Add("Email");
            dt.Columns.Add("Tekst");
            dt.Columns.Add("Czas");
            dataGridView1.DataSource = dt;

            try
            {
                client.Connect(comboBox5.Text, 995, true);
                client.Authenticate(textBox6.Text, textBox5.Text, OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
                int count = client.GetMessageCount();

                string htmlContained = "";



                if (client.Connected)
                {
                    //   for (int i = count; i > count - 100 && i >= 0; i--)
                    //     for (int i = 1;  i <=100 && i <= count; i--)
                    //  for (int i = 1; i <= count && i <= 100 ; i++)
                    // for (int i = count; i >= 100; i--)


                    for (int i = count; i > count - Convert.ToInt32(textBox4.Text) && i >= 1; i--)
                    {
                        OpenPop.Mime.Message message = client.GetMessage(i);


                        OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
                        OpenPop.Mime.MessagePart file = message.FindFirstMessagePartWithMediaType("");


                        if (html != null)
                        {
                            htmlContained = html.GetBodyAsText();
                        }
                        else
                        {
                            html = message.FindFirstPlainTextVersion();

                            htmlContained = html.GetBodyAsText();
                        }

                        string name = message.Headers.Subject;
                        if (name == "")
                        {
                            name = "Brak Tematu";
                        }

                        string nadawca = message.Headers.From.DisplayName;

                        if (nadawca == "")
                        {
                            nadawca = "Brak Informacji";
                        }

                        dt.Rows.Add(new object[] { i.ToString(), name.ToString(), nadawca.ToString(), message.Headers.From.Address, htmlContained, message.Headers.DateSent });
                    }
                }
                client.Disconnect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
            private void Visit(MessagePart MessagePart, bool isPlainText)
            {
                if (null == MessagePart) return;

                if (MessagePart.IsText)
                {
                    if (isPlainText)
                    {
                        plainText = Utils.formatText(MessagePart.GetBodyAsText());
                        fillMsgData(plainText, parent.MessageRegex);
                    }
                    else
                    {
                        text = Utils.formatText(MessagePart.GetBodyAsText());
                    }
                }
                else if (MessagePart.IsMultiPart)
                {
                    //log.Debug("MessagePart.IsMultiPart");
                    for (int i = 0; i < MessagePart.MessageParts.Count; i++)
                    {
                        Visit(MessagePart.MessageParts[i], false);
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(MessagePart.FileName)
                        && MessagePart.FileName.EndsWith("." + parent.AudioFileExtension))
                    {
                        fileMessagePart = MessagePart;

                        audioFileName = (null == fileMessagePart) ? "" : fileMessagePart.FileName;

                        //log.Debug("FileName: " + MessagePart.FileName);
                        //string fileName = parent.DirectoryForAudioFiles + Path.DirectorySeparatorChar + MessagePart.FileName;
                        //if (File.Exists(fileName))
                        //    File.Delete(fileName);
                        //MessagePart.Save(new FileInfo(parent.DirectoryForAudioFiles + Path.DirectorySeparatorChar + MessagePart.FileName));
                    }
                }
            }
Ejemplo n.º 23
0
        private async Task <object> SendAutoReply(FAQEmail aEmail)
        {
            if (aEmail != null)
            {
                EmailDownloader aDownloader = new EmailDownloader(aEmail.faq_email_id);
                aDownloader.FaqLogger = this.FaqLogger;
                List <Message> UnreadEmails = await aDownloader.UnreadEmails();

                if (UnreadEmails != null && UnreadEmails.Count > 0)
                {
                    StringBuilder builder = null;
                    foreach (Message aUnreadEmail in UnreadEmails)
                    {
                        FAQEmailsDownload newEmail = new FAQEmailsDownload()
                        {
                            download_date  = DateTime.Now
                            , email_uid    = aUnreadEmail.Headers.MessageId
                            , faq_email_id = aEmail.faq_email_id
                        };
                        this.db.FAQEmailsDownloads.Add(newEmail);
                        this.db.SaveChanges();

                        builder = new StringBuilder();
                        OpenPop.Mime.MessagePart plainText = aUnreadEmail.FindFirstPlainTextVersion();
                        if (plainText != null)
                        {
                            // We found some plaintext!
                            builder.Append(plainText.GetBodyAsText());
                        }
                        else
                        {
                            // Might include a part holding html instead
                            OpenPop.Mime.MessagePart html = aUnreadEmail.FindFirstHtmlVersion();
                            if (html != null)
                            {
                                // We found some html!
                                builder.Append(html.GetBodyAsText());
                            }
                        }
                        if (builder != null && !string.IsNullOrEmpty(builder.ToString()))
                        {
                            CanvasRespondRule answerFound = AnswerFinder.FindAnswer(AutoResponderRuleTypes.FAQs, builder.ToString());
                            if (answerFound != null)
                            {
                                SmtpPopSetting settings = (from s in db.SmtpPopSettings
                                                           where (s.smtp_pop_id == aEmail.smtp_pop_id)
                                                           select s
                                                           ).FirstOrDefault();
                                if (settings != null)
                                {
                                    string sEmailReceivedFrom = aUnreadEmail.Headers.From.MailAddress.Address;
                                    using (MailMessage mail = new MailMessage(aEmail.user_name, sEmailReceivedFrom))
                                    {
                                        using (SmtpClient client = new SmtpClient(settings.smtp_server, settings.smpt_port))
                                        {
                                            client.EnableSsl             = settings.smtp_use_ssl;
                                            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                                            client.UseDefaultCredentials = false;
                                            client.Credentials           = new NetworkCredential(aEmail.user_name, aEmail.use_password);
                                            if (!builder.ToString().Trim().ToLower().StartsWith("re:"))
                                            {
                                                mail.Subject = string.Concat("RE: ", aUnreadEmail.Headers.Subject);
                                            }
                                            mail.Body = answerFound.CanvasAnswer;
                                            try
                                            {
                                                //client.SendCompleted += (s, e) =>
                                                //{

                                                //};
                                                //client.SendAsync(mail, null);
                                                client.Send(mail);
                                                Log(string.Format("Question '{0}' replied with answer '{1}' to email account '{2}'"
                                                                  , builder.ToString(), answerFound.CanvasAnswer, sEmailReceivedFrom));
                                                AnsweredFAQ aAnswer = new AnsweredFAQ()
                                                {
                                                    answer_date_time = DateTime.Now
                                                    ,
                                                    answer_replied_with = answerFound.CanvasAnswer
                                                    ,
                                                    faq = builder.ToString()
                                                    ,
                                                    canvas_rule_id = answerFound.CanvasRuleId
                                                    ,
                                                    faq_email_id = aEmail.faq_email_id
                                                };
                                                this.db.AnsweredFAQs.Add(aAnswer);
                                                this.db.SaveChanges();
                                            }
                                            catch (Exception ex)
                                            {
                                                Log(string.Concat("EXCEPTION : ", ex.Message));
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Log(string.Format("No answer was found against FAQ '{0}'", builder.ToString()));
                                UnAnsweredFAQ unAnswered = new UnAnsweredFAQ()
                                {
                                    faq                 = builder.ToString()
                                    , faq_email_id      = aEmail.faq_email_id
                                    , to_email_address  = aUnreadEmail.Headers.From.MailAddress.Address
                                    , faq_email_subject = aUnreadEmail.Headers.Subject
                                };
                                db.UnAnsweredFAQs.Add(unAnswered);
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This method will convert this <see cref="Message"/> into a <see cref="MailMessage"/> equivalent.<br/>
        /// The returned <see cref="MailMessage"/> can be used with <see cref="System.Net.Mail.SmtpClient"/> to forward the email.<br/>
        /// <br/>
        /// You should be aware of the following about this method:
        /// <list type="bullet">
        /// <item>
        ///    All sender and receiver mail addresses are set.
        ///    If you send this email using a <see cref="System.Net.Mail.SmtpClient"/> then all
        ///    receivers in To, From, Cc and Bcc will receive the email once again.
        /// </item>
        /// <item>
        ///    If you view the source code of this Message and looks at the source code of the forwarded
        ///    <see cref="MailMessage"/> returned by this method, you will notice that the source codes are not the same.
        ///    The content that is presented by a mail client reading the forwarded <see cref="MailMessage"/> should be the
        ///    same as the original, though.
        /// </item>
        /// <item>
        ///    Content-Disposition headers will not be copied to the <see cref="MailMessage"/>.
        ///    It is simply not possible to set these on Attachments.
        /// </item>
        /// <item>
        ///    HTML content will be treated as the preferred view for the <see cref="MailMessage.Body"/>. Plain text content will be used for the
        ///    <see cref="MailMessage.Body"/> when HTML is not available.
        /// </item>
        /// </list>
        /// </summary>
        /// <returns>A <see cref="MailMessage"/> object that contains the same information that this Message does</returns>
        public MailMessage ToMailMessage()
        {
            // Construct an empty MailMessage to which we will gradually build up to look like the current Message object (this)
            MailMessage message = new MailMessage();

            message.Subject = Headers.Subject;

            // We here set the encoding to be UTF-8
            // We cannot determine what the encoding of the subject was at this point.
            // But since we know that strings in .NET is stored in UTF, we can
            // use UTF-8 to decode the subject into bytes
            message.SubjectEncoding = Encoding.UTF8;

            // The HTML version should take precedent over the plain text if it is available
            MessagePart preferredVersion = FindFirstHtmlVersion();

            if (preferredVersion != null)
            {
                // Make sure that the IsBodyHtml property is being set correctly for our content
                message.IsBodyHtml = true;
            }
            else
            {
                // otherwise use the first plain text version as the body, if it exists
                preferredVersion = FindFirstPlainTextVersion();
            }

            if (preferredVersion != null)
            {
                message.Body         = preferredVersion.GetBodyAsText();
                message.BodyEncoding = preferredVersion.BodyEncoding;
            }

            // Add body and alternative views (html and such) to the message
            IEnumerable <MessagePart> textVersions = FindAllTextVersions();

            foreach (MessagePart textVersion in textVersions)
            {
                // The textVersions also contain the preferred version, therefore
                // we should skip that one
                if (textVersion == preferredVersion)
                {
                    continue;
                }

                MemoryStream  stream      = new MemoryStream(textVersion.Body);
                AlternateView alternative = new AlternateView(stream);
                alternative.ContentId   = textVersion.ContentId;
                alternative.ContentType = textVersion.ContentType;
                message.AlternateViews.Add(alternative);
            }

            // Add attachments to the message
            IEnumerable <MessagePart> attachments = FindAllAttachments();

            foreach (MessagePart attachmentMessagePart in attachments)
            {
                MemoryStream stream     = new MemoryStream(attachmentMessagePart.Body);
                Attachment   attachment = new Attachment(stream, attachmentMessagePart.ContentType);
                attachment.ContentId = attachmentMessagePart.ContentId;

                attachment.Name = String.IsNullOrEmpty(attachment.Name) ? attachmentMessagePart.FileName : attachment.Name;
                attachment.ContentDisposition.FileName = String.IsNullOrEmpty(attachment.ContentDisposition.FileName) ? attachmentMessagePart.FileName : attachment.ContentDisposition.FileName;

                message.Attachments.Add(attachment);
            }

            if (Headers.From != null && Headers.From.HasValidMailAddress)
            {
                message.From = Headers.From.MailAddress;
            }

            if (Headers.ReplyTo != null && Headers.ReplyTo.HasValidMailAddress)
            {
                message.ReplyTo = Headers.ReplyTo.MailAddress;
            }

            if (Headers.Sender != null && Headers.Sender.HasValidMailAddress)
            {
                message.Sender = Headers.Sender.MailAddress;
            }

            foreach (RfcMailAddress to in Headers.To)
            {
                if (to.HasValidMailAddress)
                {
                    message.To.Add(to.MailAddress);
                }
            }

            foreach (RfcMailAddress cc in Headers.Cc)
            {
                if (cc.HasValidMailAddress)
                {
                    message.CC.Add(cc.MailAddress);
                }
            }

            foreach (RfcMailAddress bcc in Headers.Bcc)
            {
                if (bcc.HasValidMailAddress)
                {
                    message.Bcc.Add(bcc.MailAddress);
                }
            }

            return(message);
        }