Search code examples
c#asp.netimapgmail-imap

.Net - Error when get unread mail from Gmail by IMAP protocol


I'm trying get unread mails from Gmail by IMAP protocol. I followed this tuto : https://briancaos.wordpress.com/2012/04/24/reading-mails-using-imap-and-mailsystem-net/#comment-4999 , which recieved many good comments. But when I call

MessageCollection messages = mails.SearchParse("UNSEEN");

I got error message "index and length must refer to a location within the string". I just call a simple function, so I don't know what's wrong. For more detail, here is my code snippet:

public class MailRepository
{

    private Imap4Client _client = null;

    public MailRepository(string mailServer, int port, bool ssl, string login, string password)
    {
        if (ssl)
            Client.ConnectSsl(mailServer, port);
        else
            Client.Connect(mailServer, port);
        Client.Login(login, password);
    }

    public IEnumerable<Message> GetAllMails(string mailBox)
    {
        return GetMails(mailBox, "ALL").Cast<Message>();
    }

    public IEnumerable<Message> GetUnreadMails(string mailBox)
    {
        return GetMails(mailBox, "UNSEEN").Cast<Message>();
    }

    protected Imap4Client Client
    {
        get
        {
            if (_client == null)
                _client = new Imap4Client();
            return _client;
        }
    }

    private MessageCollection GetMails(string mailBox, string searchPhrase)
    {
        Mailbox mails = Client.SelectMailbox(mailBox);
        MessageCollection messages = mails.SearchParse(searchPhrase);
        return messages;
    }
}

Solution

  • This error may occur when your mails contain non-ASCII characters. As I don't see an easy fix here and MailSystem.NET is no longer supported, I recommend using an alternative library.

    Mailkit seems to be a good option. Also look here for further reference: https://stackoverflow.com/a/23375968