Reading gmail using OpenPop.dll errors c#

680 views Asked by At

I'm trying to read an email body from a gmail in c# using OpenPop.dll. I've tried the gmail api but i could never get it working so I tried this one. Anyways, here is my code and the error I was given.

            using (Pop3Client client = new Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate("[email protected]", "xxxxxxxx", AuthenticationMethod.UsernameAndPassword);
                int messageCount = client.GetMessageCount();
                List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
                for (int d = messageCount; d > 0; d--)
                {
                    allMessages.Add(client.GetMessage(i));
                }

Error Given on the allMessages.Add part. (runtime)

An unhandled exception of type 'OpenPop.Pop3.Exceptions.InvalidUseException' occurred in OpenPop.dll

Additional information: The messageNumber argument cannot have a value of zero or less. Valid messageNumber is in the range [1, messageCount]
1

There are 1 answers

1
Arturo Menchaca On BEST ANSWER

You're probably using this code inside another for cycle and mistook the index variables. the parameter in the GetMessagemethod should be d, not i. It should look like this:

using (Pop3Client client = new Pop3Client())
{
     client.Connect("pop.gmail.com", 995, true);
     client.Authenticate("[email protected]", "xxxxxxxx", AuthenticationMethod.UsernameAndPassword);
     int messageCount = client.GetMessageCount();
     List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
     for (int d = messageCount; d > 0; d--)
     {
          allMessages.Add(client.GetMessage(d));
     }
}