Link to home
Start Free TrialLog in
Avatar of andrewl77
andrewl77

asked on

Exchange/IMAP Email & C#/Chilikat Email

Hi,  

I have an application that is picking up the email from an exchange account through IMAP settings using Chilikat.  Currently whenever the application picks up an email it changes its status on the mail server to read, however the exchange mail box does not change status from unread to read.  

The questions I have are:
Is there a way that I can change an email in Outlook exchange email and see it through my IMAP settings?

If IMAP will not do this, does POP3 do it instead?

Here is the source code i have doing to work:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
namespace Accusoft.FSInvoicesDemo
{
    public partial class EmailInbox : Form
    {
        string CompanyId, UserId, EmailLoc = "";
        DataTable table = new DataTable();
        static string HostName, Port, UserName, Password = "";
        DataTable dtEmailConfig = new DataTable();
        public EmailInbox(DataTable dtEmailConfiguration, string Uid, string CompId, string Email)
        {
            InitializeComponent();
            try
            {
                CompanyId = CompId;
                UserId = Uid;
                button3.Visible = true;
                btnCheckAll.Visible = true;
                dtEmailConfig = dtEmailConfiguration;
                foreach (DataRow o in dtEmailConfig.Select("Name = 'pop3'"))
                {
                    //  Console.WriteLine("\t" + o["HostName"] + "\t" + o["Port"] + "\t" + o["Username"] + "\t" + o["Password"]);
                    HostName = Convert.ToString(o["HostName"]);
                    Port = Convert.ToString(o["Port"]);
                    UserName = Convert.ToString(o["Username"]);
                    Password = Convert.ToString(o["Password"]);
                }
                foreach (DataRow o in dtEmailConfig.Select("Name = 'imap'"))
                {
                    //  Console.WriteLine("\t" + o["HostName"] + "\t" + o["Port"] + "\t" + o["Username"] + "\t" + o["Password"]);

                    HostName = Convert.ToString(o["HostName"]);
                    Port = Convert.ToString(o["Port"]);
                    UserName = Convert.ToString(o["Username"]);
                    Password = Convert.ToString(o["Password"]);
                }
                foreach (DataRow o in dtEmailConfig.Select("Hostname = 'pop-mail.outlook.com'"))
                {
                    //  Console.WriteLine("\t" + o["HostName"] + "\t" + o["Port"] + "\t" + o["Username"] + "\t" + o["Password"]);
                    HostName = Convert.ToString(o["HostName"]);
                    Port = Convert.ToString(o["Port"]);
                    UserName = Convert.ToString(o["Username"]);
                    Password = Convert.ToString(o["Password"]);
                }
                EmailLoc = Email;
                table.Columns.Add("Subject", typeof(string));
                table.Columns.Add("MetaData", typeof(object));
                table.Columns.Add("Count Attachment", typeof(int));
                GetEmailFromEmailServer(HostName, Port, UserName, Password);
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogFile(ex.Message, ex.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, this.FindForm().Name);
            }
        }
        public void GetEmailFromEmailServer(string HostName, string Port, string UserName, string Password)
        {
            try
            {
                 

                string appPath = Application.StartupPath;
                string emailidPath = @"seenUidls.txt";
                string fullpath = Path.Combine(appPath, emailidPath);

                 
                //  The mailman object is used for receiving (POP3)
                //  and sending (SMTP) email.
                Chilkat.MailMan mailman = new Chilkat.MailMan();
                //  Any string argument automatically begins the 30-day trial.
                bool success;
                success = mailman.UnlockComponent("30-day trial");
                if (success != true)
                {
                    MessageBox.Show("Component unlock failed");
                    return;
                }
                //  Set the POP3 server's hostname
                mailman.MailHost = HostName;
                mailman.MailPort = Convert.ToInt32(Port);
                //  Set the POP3 login/password.
                mailman.PopUsername = UserName.Trim().ToString();
                mailman.PopPassword = DecodeFrom64(Password);
                /////////////////
                //  You may keep a list of already-seen UIDLs in a text file:
                //  If this is the first time you're running this example,
                //  create an empty text file named "seenUidls.txt";
                Chilkat.StringArray saSeenUidls = new Chilkat.StringArray();
                success = saSeenUidls.LoadFromFile(fullpath);
                if (success != true)
                {
                    Console.WriteLine("failed to load seenUidls.txt");
                    return;
                }
                //  Get the complete list of UIDLs on the mail server.
                Chilkat.StringArray saUidls = null;
                saUidls = mailman.GetUidls();

                if (saUidls == null)
                {
                    Console.WriteLine(mailman.LastErrorText);
                    return;
                }
                //  Create a new string array object (it's an object, not an actual array)
                //  and add the UIDLs from saUidls that aren't already seen.
                Chilkat.StringArray saUnseenUidls = new Chilkat.StringArray();
                int k;
                int p;
                p = saUidls.Count;
                for (k = 0; k <= p - 1; k++)
                {
                    if (saSeenUidls.Contains(saUidls.GetString(k)) != true)
                    {
                        saUnseenUidls.Append(saUidls.GetString(k));
                    }

                }

                if (saUnseenUidls.Count == 0)
                {
                    button3.Visible = false;
                    btnCheckAll.Visible = false;
                    MessageBox.Show("No unseen emails found!");

                    return;
                }
                ///////////// 

                Chilkat.EmailBundle bundle = null;
                //  Copy the all email from the user's POP3 mailbox        
                //  into a bundle object.  The email remains on the server.             
                Cursor.Current = Cursors.WaitCursor;
                bundle = mailman.FetchMultiple(saUnseenUidls);

                //bundle = mailman.CopyMail(); 
                Cursor.Current = Cursors.AppStarting;
                if (bundle == null)
                {
                    MessageBox.Show(mailman.LastErrorText);
                    return;
                }
                //string dirPath;
                //dirPath = "c:/myAttachments";
                int i;
                Chilkat.Email email = null;
                for (i = 0; i <= bundle.MessageCount - 1; i++)
                {
                    email = bundle.GetEmail(i);
                    //  You may save all the attachments to the specified directory
                    //  by calling SaveAllAttachments.
                    //  The SaveAllAttachments method will automatically create the directory
                    //  if it does not already exist.
                    //success = email.SaveAllAttachments(dirPath);
                    //if (success != true)
                    //{
                    //    MessageBox.Show(email.LastErrorText);
                    //    return;
                    //}
                    //  The OverwriteExisting property controls whether already-existing files
                    //  are automatically overwritten.  By default, it is set to true so that existing
                    //  files will be overwritten.
                    //  Setting OverwriteExisting = false will cause the attachment-saving methods to generate
                    //  unique filenames if a file with the same name already exists.  The actual filename(s)
                    //  saved will be present by calling GetAttachmentFilename for each attachment *after*
                    //  saving.
                    //  For example...
                    //email.OverwriteExisting = false;
                    //success = email.SaveAllAttachments(dirPath);
                    //if (success != true)
                    //{
                    //    MessageBox.Show(email.LastErrorText);
                    //    return;
                    //}
                    int n;
                    n = email.NumAttachments;
                    int j;
                    string Subject = email.Subject;
                    table.Rows.Add(Subject, email, n);
                    //for (j = 0; j <= n - 1; j++)
                    //{
                    //    //  If the attachment filename was changed to prevent overwriting,
                    //    //  GetAttachmentFilename will return the new filename.
                    //    //textBox1.Text += email.GetAttachmentFilename(j) + "\r\n";
                    //}
                    //  You may also save individual attachments:
                    //for (j = 0; j <= n - 1; j++)
                    //{
                    //    //textBox1.Text += "Original Filename: "
                    //    //     + email.GetAttachmentFilename(j) + "\r\n";
                    //    success = email.SaveAttachedFile(j, dirPath);
                    //    if (success != true)
                    //    {
                    //        MessageBox.Show(email.LastErrorText);
                    //        return;
                    //    }
                    //    //  If OverwriteExisting = true, the saved filename will always equal the original filename,
                    //    //  unless there are characters present in the filename that are not allowed by Windows,
                    //    //  such as * ? < > | etc.  In those cases the illegal characters are either removed or replaced
                    //    //  with underscore characters to allow the file to be saved.
                    //    //  textBox1.Text += "Saved Filename: " + email.GetAttachmentFilename(j) + "\r\n";
                    //}
                }
                saUidls.SaveToFile(fullpath);
                dataGridView1.DataSource = table.DefaultView;
                DataGridViewCheckBoxColumn checkBoxColumn3 = new DataGridViewCheckBoxColumn();
                checkBoxColumn3.HeaderText = "Check";
                checkBoxColumn3.Width = 60;
                checkBoxColumn3.Name = "Check";
                dataGridView1.Columns.Insert(3, checkBoxColumn3);
                dataGridView1.Columns["Subject"].Width = 710;
                dataGridView1.Columns["MetaData"].Visible = false;
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogFile(ex.Message, ex.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, this.FindForm().Name);
            }
        }


    
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string appPath = Application.StartupPath;
                string SaveemailidPath = @"myAttachments";
                string fullpath = Path.Combine(appPath, SaveemailidPath);

                // string dirPath;
                // dirPath = "c:/myAttachments";
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    bool ChkMail = (bool)dataGridView1.Rows[i].Cells["Check"].FormattedValue;
                    if (ChkMail == true)
                    {
                        Chilkat.Email email = (Chilkat.Email)dataGridView1.Rows[i].Cells["MetaData"].Value;
                        email.SaveAllAttachments(fullpath);
                    }
                }
                MDIParent2 obj = new MDIParent2("A");

                string[] filePaths = Directory.GetFiles(fullpath, "*.pdf");

                //After getting delete all files

                // Array.ForEach(Directory.GetFiles(fullpath, "*.pdf"), File.Delete);
                // System.IO.Directory.Delete(fullpath, true);

                //end delete
                this.Close();




                obj.EmailAttachFileProcess(filePaths, CompanyId, UserId, EmailLoc);
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogFile(ex.Message, e.ToString(), ((Control)sender).Name, this.FindForm().Name);

            }
        }
    
        private void btnCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                    chk.Value = !(chk.Value == null ? false : (bool)chk.Value); //because chk.Value is initialy null
                }
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogFile(ex.Message, e.ToString(), ((Control)sender).Name, this.FindForm().Name);
                //throw ex;
            }
        }
        public string DecodeFrom64(string encodedData)
        {
            string result = "";
            try
            {
                System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();
                byte[] todecode_byte = Convert.FromBase64String(encodedData);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                result = new String(decoded_char);
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogFile(ex.Message, ex.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, this.FindForm().Name);
            }
            return result;
        }

        private void EmailInbox_Load(object sender, EventArgs e)
        {

        }
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial