using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;
using System.Threading;
using System.Xml;
using onlyconnect;

namespace OutlookExpress_V1._._
{
    public partial class SendMail : Form
    {
        private string PSN = "";
        private string SSN = "";
        private string PP = "";
        private string SP = "";
        private string UN = "";
        private string PW = "";
        ContextMenu cm = new ContextMenu();
        ArrayList attachments;
        public SendMail()
        {
            this.attachments = new ArrayList();
            InitializeComponent();
            GetMailServerSetting();
        }

        private void MailMessage_Click(object sender, EventArgs e)
        {

        }

        private void SendMail_Load(object sender, EventArgs e)
        {
            this.MailMessage.IsDesignMode = true;
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            this.MailMessage.Print(true, string.Empty, false);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.MailMessage.Cut();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            this.MailMessage.SelectAll();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            this.MailMessage.Copy();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            this.MailMessage.Paste();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            this.MailMessage.HtmlDocument2.ExecCommand("bold", false, null);
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            this.MailMessage.HtmlDocument2.ExecCommand("underline", false, null);
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            this.MailMessage.HtmlDocument2.ExecCommand("italic", false, null);
        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripTextBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetSelectionFont();
        }

        private void toolStripTextBox2_Click(object sender, EventArgs e)
        {

        }

        private void toolStripTextBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetSelectionFont();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            IHTMLElement el = null;
            try
            {
                if (this.MailMessage.IsDesignMode)
                {
                    el = MailMessage.CurrentElement;
                    if (el != null && el.tagName != "BODY")
                    {
                        el.outerHTML = "<h1>" + el.innerHTML + "</h1>";
                    }
                }
            }
            catch (Exception exc)
            {
                string sMessage = "Could not apply heading: " + exc.Message;
                if (el != null)
                {
                    sMessage += " The possible reason is the the tag is " + el.tagName + ".";
                }
                MessageBox.Show(sMessage);
            }

        }

        private void MailMessage_BeforeNavigate(object s, BeforeNavigateEventArgs e)
        {
            e.Cancel = true;
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            this.MailMessage.Print(true, string.Empty, false);
        }

        private void panel4_Paint(object sender, PaintEventArgs e)
        {

        }

        private void PHeader_Paint(object sender, PaintEventArgs e)
        {

        }

        private void statusStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void ProgressLabel_Click(object sender, EventArgs e)
        {

        }

        private void panel6_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel10_Paint(object sender, PaintEventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void lblSubject_Click(object sender, EventArgs e)
        {

        }

        private void panel5_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel9_Paint(object sender, PaintEventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnBCC_Click(object sender, EventArgs e)
        {

        }

        private void panel8_Paint(object sender, PaintEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnCC_Click(object sender, EventArgs e)
        {

        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel7_Paint(object sender, PaintEventArgs e)
        {

        }

        private void txtTo_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnTo_Click(object sender, EventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            SendEmail();
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void Prt_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Pbt_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Plt_Paint(object sender, PaintEventArgs e)
        {

        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                this.MailMessage.SelectionBackColor = dialog.Color;
                toolStripButton11.Image = CreateFontColorIcon(dialog.Color);
            }
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                this.MailMessage.SelectionForeColor = dialog.Color;
                toolStripButton12.Image = CreateFontColorIcon(dialog.Color);
            }
        }
        private Bitmap CreateFontColorIcon(Color color)
        {
            Bitmap bmp = new Bitmap(2, 2);

            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 12; y < bmp.Height; y++)
                {
                    bmp.SetPixel(x, y, color);
                }
            }

            return bmp;
        }
        private void SetSelectionFont()
        {
            try
            {
                System.Drawing.FontStyle style = System.Drawing.FontStyle.Bold;
                this.MailMessage.DefaultComposeSettings.Enabled = true;
                this.MailMessage.DefaultComposeSettings.DefaultFont = new Font(toolStripTextBox1.Text.ToString(), Convert.ToInt32(toolStripTextBox2.Text));
                this.MailMessage.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private Bitmap CreateFontBackColorIcon(Color color)
        {
            Bitmap bmp = new Bitmap(2, 2);

            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 12; y < bmp.Height; y++)
                {
                    bmp.SetPixel(x, y, color);
                }
            }

            return bmp;
        }
        private void panel11_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void panel12_Paint(object sender, PaintEventArgs e)
        {

        }
        private void SendEmail(object mail_msg)
        {
            try
            {
                MailMessage mail_message = (MailMessage)mail_msg;

                SmtpClient smtp = new SmtpClient(SSN, Convert.ToInt32(SP));
                smtp.UserName = UN;
                smtp.Password = PW;

                this.EnableDisableSendButton(false);

                smtp.ConnectionEstablishing += new ConnectEventHandler(smtp_ConnectionEstablishing);
                smtp.ConnectionEstablished += new ConnectEventHandler(smtp_ConnectionEstablished);
                smtp.AuthenticationBegan += new AuthenticateEventHandler(smtp_AuthenticationBegan);
                smtp.AuthenticationFinished += new AuthenticateEventHandler(smtp_AuthenticationFinished);
                smtp.StartedDataTransfer += new DataTransferEventHandler(smtp_StartedDataTransfer);
                smtp.EndedDataTransfer += new DataTransferEventHandler(smtp_EndedDataTransfer);
                smtp.Disconnected += new DisconnectEventHandler(smtp_Disconnected);

                smtp.SendMail(mail_message);
                MessageBox.Show(this, "Email message has sent.", "Unsent Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (SmtpClientException obj)
            {
                //MessageBox.Show(this, obj.ErrorMessage, "Unsent Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //this.EnableDisableSendButton(true);
                this.ProgressLabel.Text = obj.ErrorMessage.ToString();
            }
        }
        // The delegate used to update Status Bar
        private delegate void UpdateStatusBarEventHandler(string text);

        private void UpdateStatusBar(string text)
        {
            if (this.statusStrip.InvokeRequired)
            {
                UpdateStatusBarEventHandler obj = new UpdateStatusBarEventHandler(this.UpdateStatusBar);
                this.Invoke(obj, new object[] { text });
            }
            else
            {
                this.ProgressLabel.Text = text;
            }
        }

        private delegate void EnableDisableEventHandler(bool enable);

        private void EnableDisableSendButton(bool enable)
        {

            //this.btnSend.Enabled = enable;

        }

        void smtp_Disconnected(object sender, string Server)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DisconnectEventHandler discon = new DisconnectEventHandler(this.smtp_Disconnected);
                this.Invoke(discon, new object[] { sender, Server });
            }
            else
            {
                this.ProgressLabel.Text = "Disconnected with the smtp server \"" + Server + "\"";
                Thread.Sleep(500);
               // this.btnSend.Enabled = true;
                this.ProgressLabel.Text = "Unsent Message";
            }
        }

        void smtp_EndedDataTransfer(object sender)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DataTransferEventHandler data = new DataTransferEventHandler(this.smtp_EndedDataTransfer);
                this.Invoke(data, new object[] { sender });
            }
            else
            {
                this.ProgressLabel.Text = "Email message has sent";
            }
        }

        void smtp_StartedDataTransfer(object sender)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DataTransferEventHandler data = new DataTransferEventHandler(this.smtp_StartedDataTransfer);
                this.Invoke(data, new object[] { sender });
            }
            else
            {
                this.ProgressLabel.Text = "Sending email message";
            }
        }

        void smtp_AuthenticationFinished(object sender, string userName)
        {
            if (this.statusStrip.InvokeRequired)
            {
                AuthenticateEventHandler auth = new AuthenticateEventHandler(this.smtp_AuthenticationFinished);
                this.Invoke(auth, new object[] { sender, userName });
            }
            else
            {
                this.ProgressLabel.Text = "Verification is completed";
            }
        }

        void smtp_AuthenticationBegan(object sender, string userName)
        {
            if (this.statusStrip.InvokeRequired)
            {
                AuthenticateEventHandler auth = new AuthenticateEventHandler(this.smtp_AuthenticationBegan);
                this.Invoke(auth, new object[] { sender, userName });
            }
            else
            {
                this.ProgressLabel.Text = "Verifying user name and password";
            }
        }

        void smtp_ConnectionEstablishing(object sender, string Server, int Port)
        {
            if (this.statusStrip.InvokeRequired)
            {
                ConnectEventHandler con = new ConnectEventHandler(this.smtp_ConnectionEstablishing);
                this.Invoke(con, new object[] { sender, Server, Port });
            }
            else
            {
                this.ProgressLabel.Text = "Connecting to smtp server \"" + Server + "\" on port " + Port;
            }
        }

        void smtp_ConnectionEstablished(object sender, string Server, int Port)
        {
            if (this.statusStrip.InvokeRequired)
            {
                ConnectEventHandler con = new ConnectEventHandler(this.smtp_ConnectionEstablished);
                this.Invoke(con, new object[] { sender, Server, Port });
            }
            else
            {
                this.ProgressLabel.Text = "Connection is established with the smtp server \"" + Server + "\"";
            }
        }

        private void GetMailServerSetting()
        {
            try
            {
                if (File.Exists("PerlLookUpS.xml"))
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(@"PerlLookUpS.xml");
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    PSN = dt.Rows[0][0].ToString();
                    PP = dt.Rows[0][1].ToString();
                    SSN = dt.Rows[0][2].ToString();
                    SP = dt.Rows[0][3].ToString();
                    UN = dt.Rows[0][4].ToString();
                    PW = dt.Rows[0][5].ToString();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SendEmail()
        {
            if (this.CheckInputValidation(SSN, SP, UN, PW, UN, txtTo.Text, txtCC.Text, txtBCC.Text))
            {
                if (this.EmailValidation(UN))
                {
                    bool isRecipient = false;

                    if (this.txtTo.Text.Length > 0)
                    {
                        if (this.RecipientsEmailValidation(this.txtTo.Text))
                        {
                            isRecipient = true;
                        }
                        else
                        {
                            MessageBox.Show(this, "Recipients' email address is not in the correct format, in \"To: \" field.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }

                    if (this.txtCC.Text.Length > 0)
                    {
                        if (!(this.RecipientsEmailValidation(this.txtCC.Text)))
                        {
                            MessageBox.Show(this, "Recipients' email address is not in the correct format, in \"Cc: \" field.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            isRecipient = true;
                        }
                    }

                    if (this.txtBCC.Text.Length > 0)
                    {
                        if (!(this.RecipientsEmailValidation(this.txtBCC.Text)))
                        {
                            MessageBox.Show(this, "Recipients' email address is not in the correct format, in \"Bcc: \" field.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            isRecipient = true;
                        }
                    }
                    if (Internet.IsConnectedToInternet())
                    {
                        if (isRecipient == true)
                        {
                            Rtf2Html rtf = new Rtf2Html();
                            string Html = this.MailMessage.Text;

                            MailMessage mail_message = new MailMessage();
                            mail_message.From = UN;
                            mail_message.To = this.txtTo.Text;
                            mail_message.CC = this.txtCC.Text;
                            mail_message.BCC = this.txtBCC.Text;
                            mail_message.Subject = this.txtSubject.Text;
                            mail_message.MailType = MailEncodingType.HTML;
                            mail_message.MailPriority = MailSendPriority.NORMAL;
                            mail_message.Message = Html;
                            mail_message.Attachments = this.attachments;

                            Thread thread = new Thread(new ParameterizedThreadStart(this.SendEmail));
                            thread.Start(mail_message);
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "You must connect to the internet.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show(this, "Sender email address is not in the correct format.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private bool CheckInputValidation(string smtp_server, string smtp_port, string user_name, string password, string from, string to, string cc, string bcc)
        {
            if (smtp_server.Equals(""))
            {
                MessageBox.Show(this, "You must provide smtp server address.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (smtp_port.Equals(""))
            {
                MessageBox.Show(this, "You must provide smtp port number.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (user_name.Equals(""))
            {
                MessageBox.Show(this, "You must provide username.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (password.Equals(""))
            {
                MessageBox.Show(this, "You must provide password.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if (from.Equals(""))
            {
                MessageBox.Show(this, "You must provide sender email address.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else if ((!(to.Equals(""))) || (!(cc.Equals(""))) || (!(bcc.Equals(""))))
            {
                return true;
            }
            else if (to.Equals("") && cc.Equals("") && bcc.Equals(""))
            {
                MessageBox.Show(this, "You must provide recipient email address.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            return true;
        }

        private bool RecipientsEmailValidation(string recipient)
        {
            string[] splits = recipient.Split(new char[] { ',', ';' });

            for (int i = 0; i < splits.Length; i++)
            {
                if (this.EmailValidation(splits[i]))
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

        private bool EmailValidation(string email)
        {
            Regex regx = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase);
            if (regx.IsMatch(email))
            {
                return true;
            }
            return false;
        }

        private void toolStripButton14_Click(object sender, EventArgs e)
        {
            this.MailMessage.ShowFindDialog();
        }

        private void toolStripButton15_Click(object sender, EventArgs e)
        {
            this.MailMessage.ClearSelectionFormatting();
        }

        private void btnSend_Click_1(object sender, EventArgs e)
        {
            SendEmail();
        }
    }
}
