Checking outlook email from a C# Windows Form

Checking email from a Windows form in C#

Good morning experts,

I am trying to find a way to check email coming through our Outlook exchange (2007) . I came across the  code listed below on the internet.
The code works up to a point. It reaches the inbox folder and display one of the emails in it.
The problems is it does this at random. It doesn’t retrieve the last email or even today’s email. What is more, when the form is reloaded and the code is run again, the same email is being displayed.
Please advise. Thank you


        private void checkIncomingMail()
        {
            Outlook.Application OutlookApp = new Outlook.Application();
           
            this.txtBody.Visible = true; // email text
            this.txtTicketBody.Visible = false;
            this.lblSubject.Text = "Send To";

            Outlook._Application myApp = new Outlook.Application();
            Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
            Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            if (myInbox.Items.Count > 0)
            {
                this.txtSubject.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Subject;
                lblSubject.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Subject;
                //Grab the Attachment Name
                if (((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Attachments.Count > 0)
                {
                    lblAttachmentName.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Attachments[1].FileName;
                }
                else
                {
                    lblAttachmentName.Text = "No Attachment";
                }
                // Grab the Body
                txtBody.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Body;
                // Sender Name
                lblSenderName.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).SenderName;
                // Sender Email
                lblSenderEmail.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).SenderEmailAddress;
                // Creation date
                lblCreationdate.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).CreationTime.ToString();

            }
            else
            {
                MessageBox.Show("There are no emails in your Inbox.");
            }
        }
adamtraskAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Naitik GamitSoftware DeveloperCommented:
Look at this project of access outlook email from a C# Windows Form:

http://www.programminghelp.com/dotnet/access-your-email-within-outlook-final-part-c/
0
Éric MoreauSenior .Net ConsultantCommented:
You are accessing Items[1]. You need to loop through the Items collection.
0
adamtraskAuthor Commented:
Naitik Gamit, Thank you for the link. I believe this is the same code I was referring to.
 It does work, but only shows one email without any option to show others. It displays the same email each time I click on the "Access Email" button. There is no guide on how we can develop this further.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

KimputerCommented:
You need to tell us what you exactly want the code to do. You only told us it shows one email (only logical), and that you want to "develop this furter". But that doesn't give us ANY information at all what you really want it to do, except maybe get only the newest email.
0
adamtraskAuthor Commented:
Sorry for not being clear. I want a way to show each email that has not been read.
0
Éric MoreauSenior .Net ConsultantCommented:
You need to loop through the Items collection.
0
adamtraskAuthor Commented:
Sorry Éric Moreau, I didn't see your earlier post.... will try that
0
KimputerCommented:
How do you want it to show. Your form only "supports" one message. Do you want to keep clicking on a NEXT button, or do you want to change the form to a list or something.
0
adamtraskAuthor Commented:
Yes, clicking on a next button would be a good solution. Thanks.
0
adamtraskAuthor Commented:
Ok,

With further research I found the code listed below. It works fine as far as displaying each email. The only problem is that it displays the emails in a messageBox which display one email then pause until the user clicks OK then moves on to display the next email.
I need to display each message in a designated textBox for messages. I need to make the click event move from one email to the next.
0
adamtraskAuthor Commented:
Ok,

With further research I found the code listed below. It works fine as far as displaying each email. The only problem is that it displays the emails in a message Box which display one email then pause until the user clicks OK then moves on to display the next email.
I need to display each message in a designated text Box for messages. I need to make the click event move from one email to the next.

 private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.ApplicationClass();

            Microsoft.Office.Interop.Outlook.NameSpace NS = app.GetNamespace("MAPI");

            Microsoft.Office.Interop.Outlook.MAPIFolder objFolder = NS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

           Microsoft.Office.Interop.Outlook.MailItem objMail;
           
            Microsoft.Office.Interop.Outlook.Items oItems;

            oItems = objFolder.Items;

            objMail = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetFirst();

            for (int i = 1; i <= oItems.Count; i++)
            {
                objMail = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetNext();
             
              MessageBox.Show(objMail.Body.ToString());
             
             
             
            }

        }
0
Éric MoreauSenior .Net ConsultantCommented:
you will need to replace:
MessageBox.Show(objMail.Body.ToString());

Open in new window


with:
YourDesignatedTB.Text = objMail.Body.ToString();

Open in new window

0
adamtraskAuthor Commented:
I did that. The problem is the textBox would display the emails, one after the other without a pause. The messageBox pauses the flow of emails until you click OK.
But not the textBox!
I spent a good time trying to find a way around this without success.
0
Éric MoreauSenior .Net ConsultantCommented:
You cannot put all that code into the button's click event. The reason is that every time you click on it, the full process starts all over again.

What you need to do is to read all the message once (when the form opens for example) and then loop through the messages in buttons.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        Microsoft.Office.Interop.Outlook.Items oItems;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.NameSpace NS = app.GetNamespace("MAPI");
            Microsoft.Office.Interop.Outlook.MAPIFolder objFolder = NS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

            oItems = objFolder.Items;

            btnNext.PerformClick();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            var objMail = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetPrevious();
            if (objMail != null)
            {
                textBox1.Text = objMail.Body;
                textBox2.Text = objMail.Subject;
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            var objMail = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetNext();
            if (objMail != null)
            {
                textBox1.Text = objMail.Body;
                textBox2.Text = objMail.Subject;
            }
        }
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
adamtraskAuthor Commented:
Thanks Éric Moreau....
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Outlook

From novice to tech pro — start learning today.