C# .Net-通过IMAP协议从Gmail获取未读邮件时出错

C# .Net-通过IMAP协议从Gmail获取未读邮件时出错,c#,asp.net,imap,gmail-imap,C#,Asp.net,Imap,Gmail Imap,我正在尝试通过IMAP协议从Gmail获取未读邮件。我跟着这首芭蕾舞曲,得到了很多好评。 但是当我打电话的时候 MessageCollection messages=mails.SearchParse(“不可见”) 我收到错误消息“索引和长度必须引用字符串中的位置”。 我只调用了一个简单的函数,所以我不知道出了什么问题。有关更多详细信息,请参见我的代码片段: public class MailRepository { private Imap4Client _client = null

我正在尝试通过IMAP协议从Gmail获取未读邮件。我跟着这首芭蕾舞曲,得到了很多好评。 但是当我打电话的时候

MessageCollection messages=mails.SearchParse(“不可见”)

我收到错误消息“索引和长度必须引用字符串中的位置”。 我只调用了一个简单的函数,所以我不知道出了什么问题。有关更多详细信息,请参见我的代码片段:

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;
    }
}
公共类邮件存储库
{
私有Imap4Client _client=null;
公共邮件存储库(字符串邮件服务器、int端口、bool ssl、字符串登录、字符串密码)
{
如果(ssl)
ConnectSsl(邮件服务器,端口);
其他的
Client.Connect(邮件服务器、端口);
Client.Login(登录名,密码);
}
公共IEnumerable GetAllMail(字符串邮箱)
{
返回GetMail(邮箱,“全部”).Cast();
}
公共IEnumerable GetUnderMails(字符串邮箱)
{
返回GetMail(邮箱,“未看到”).Cast();
}
受保护的IMAP4客户端
{
得到
{
如果(_client==null)
_client=新的Imap4Client();
返回客户;
}
}
private MessageCollection GetMail(字符串邮箱、字符串搜索短语)
{
邮箱邮件=客户端。选择邮箱(邮箱);
MessageCollection messages=mails.SearchParse(searchPhrase);
返回消息;
}
}

当您的邮件包含非ASCII字符时,可能会发生此错误。由于我在这里看不到简单的修复方法,而且MailSystem.NET不再受支持,我建议使用替代库


这似乎是个不错的选择。也可以在这里查看更多参考资料:

好主意!我已经试过其他图书馆了。我发现IMAPX是一个不错的选择。不过,谢谢你的回复