1

我正在尝试使用 MailSystem.NET 库在电子邮件到达我的收件箱后立即获取它们。一切正常 IMAP 客户端已连接,但我的 NewMessageReceived 事件从未被触发。

请帮忙

下面是代码:

public static Imap4Client _imap = new Imap4Client();
    public string SenderEmailAddress = System.Configuration.ConfigurationManager.AppSettings["EmailAddress"];
    public string SenderEmailPassword = System.Configuration.ConfigurationManager.AppSettings["EmailPassword"];
    public static Mailbox inbox = new Mailbox();
    protected void Application_Start()
    {

        var worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(StartIdleProcess);

        if (worker.IsBusy)
            worker.CancelAsync();

        worker.RunWorkerAsync();
    }

    private void StartIdleProcess(object sender, DoWorkEventArgs e)
    {
        try
        {


            if (_imap != null && _imap.IsConnected)
            {
                _imap.StopIdle();
                _imap.Disconnect();
            }

            _imap = new Imap4Client();
            _imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
            _imap.ConnectSsl("imap.gmail.com", 993);
            _imap.Login(SenderEmailAddress, SenderEmailPassword);

            inbox = _imap.SelectMailbox("inbox");
            int[] ids = inbox.Search("UNSEEN");


            inbox.Subscribe();

            _imap.StartIdle();
        }
        catch (Exception ex)
        {

        }
    }

    public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
    {
        int offset = e.MessageCount - 2;
        Message message = inbox.Fetch.MessageObject(offset);
        Debug.WriteLine("message subject: " + message.Subject);
        // Do something with the source...

        _imap.StopIdle();
    }
4

1 回答 1

1

我不能告诉你确切的原因,但似乎从 NewMessageReceived 事件与 imapclient 交互不起作用。

在 NewMessageReceived 调用 _imap.StopIdle() 然后继续您的主执行流程并重新启动空闲。然后使用布尔值完全退出循环。

private bool _stop = false;

private void StartIdle(object sender, DoWorkEventArgs e)
{
   //Setup client
   _imap = new Imap4Client();
   _imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
   StartRepeatExecution();
}

public void StartRepeatExecution()
{
   _imap.StartIdle();
   if(_stop) return;

   //Handle your new messages here! dummy code
    var mailBox = _imap.SelectMailBox("inbox");
    var messages = mailBox.SearchParse("").Last();

   StartRepeatExecution();
}

public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
{
   //StopIdle will return to where _imap.StartIdle() was called.
   _imap.StopIdle();
}

public void StopRepeatExecution()
{ 
   _stop = true;
}
于 2021-02-02T16:10:15.557 回答